数据如何从自定义指令视图传递到控制器?

时间:2014-09-15 13:17:22

标签: javascript html angularjs

指令模板的代码     // “textBox.html”

<div class="well">
    <label class="control-label">Text</label>
    <div class="controls">
        <input id="label" type="text" class="txt span3" ng-model="label" placeholder='Label for text field...'>
        <input type="text" class="span3" ng-model="value" placeholder='Default value...'>
        <input type="text" class="span3" ng-model="helpText" placeholder="Help text...">
        <input type="checkbox" class="span1"  ng-model="required" ng-true-value="true" ng-false-value="false">Required
        <input type="checkbox" class="span1"  ng-model="advanced" ng-true-value="true" ng-false-value="false">Advanced?
        <img src="../../images/bullet_cross.png" alt="Remove" style="cursor: pointer" id="text" border="0" ng-click="deleteField($event)">
    </div>

</div>

指令在主html页面中使用这样的

//"algorithm.html"
<text-box></text-box>

自定义指令的控制器

//"controller.js"
var algorithm = angular.module('algorithmController',[]);

/***********directive to render text field***********/
algorithm.directive('textField' , function(){
    return{
        restrict: 'E',
        templateUrl: '../partials/algorithm/textBox.html',
        require: 'ngModel',
        replace: true,
        link: function(scope, iElement, iAttrs, ngModelCtrl) {
            // how should i get updated data(i.e. if user change after typing) over here entered by user??
        }
    };
});

1 个答案:

答案 0 :(得分:0)

您可以使用'='语法创建隔离范围,这将创建与控制器和指令的双向绑定。您甚至不需要在指令中使用ngModel。

.directive("textField", function () {

        return {
            restrict : "E",
            template : "<input type='text' ng-model='val'/>",
            scope : {
                val : "="
            }
        };

    });

这是一个非常简单的例子,可以满足您的要求;

http://jsfiddle.net/smaye81/xaohrv53/2/

相关问题