Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs ng模型和指令之间的双向数据绑定_Angularjs_Angularjs Directive - Fatal编程技术网

Angularjs ng模型和指令之间的双向数据绑定

Angularjs ng模型和指令之间的双向数据绑定,angularjs,angularjs-directive,Angularjs,Angularjs Directive,案例: 我试图通过一个指令观察选择列表的变化,然后根据所选值添加html,但由于某些原因,我无法观察链接函数中的变化。有什么想法吗?谢谢 HTML <select ng-model="selected" ng-options="item as item.type for item in itemsList"></select> <d-input type="selected.type"></d-input> JS app.directive

案例:

我试图通过一个指令观察选择列表的变化,然后根据所选值添加html,但由于某些原因,我无法观察链接函数中的变化。有什么想法吗?谢谢

HTML

<select ng-model="selected" ng-options="item as item.type for item in itemsList"></select>

<d-input type="selected.type"></d-input>

JS

app.directive('dInput', function($compile) {
    return {
        restrict: 'E',
        scope : {
            type : '=',
        } ,
        template : '<div></div>',
         link : function (scope, element, attrs) {
            scope.$watch(scope.type, function() {
            var tmplt = '' ;
            if (scope.type == 'input')
                tmplt = '<input type ="text" name="inputname" value="0">';
            if (scope.type== 'select')
                tmplt = '<select ><option> option1</option><option>option2</option></select>';
            if (scope.type == 'radio')
                tmplt = '<input type ="radio" name="inputname" value="0">';

           element.html(tmplt);
           $compile(element.contents())(scope);

            });                                   
        },  
    } 
});
app.directive('dInput',函数($compile){
返回{
限制:'E',
范围:{
类型:“=”,
} ,
模板:“”,
链接:函数(范围、元素、属性){
scope.$watch(scope.type,function(){
var-tmplt='';
如果(scope.type==“输入”)
tmplt='';
if(scope.type==“选择”)
tmplt=‘选项1选项2’;
如果(scope.type=='radio')
tmplt='';
html(tmplt);
$compile(element.contents())(范围);
});                                   
},  
} 
});

您需要更改
$watch
功能的第一个参数:

scope.$watch(function () {
    return scope.type;
}, function() {

    ....
});

@RawanNj看一看
$watch
部分和示例:好的:)另一个问题,scope对象中的“=”如何,起初我认为这适用于绑定,我不需要watch来监视更改,所以每当ng model的值更改时,它都会更改。。是否只传递参数并能够从范围中更改它,但不能监视更改?@RawanNj
=
表示双向绑定。您可以更改指令/控制器/视图中的值,更改将反映在另一端。@OmariAhron正是这样,当它从视图中更改时,它应该反映在指令中!那我为什么需要这个watch@RawanNj啊,对不起,刚才我明白你的意思了。它应该可以工作,如果不行,您可以尝试查看所选的
,而不是所选的
。键入
。如果这仍然不起作用,尝试创建一个小提琴和一个新问题:)