2016-01-20 84 views
1

我无法获得在AngularJS指令中工作的两种数据绑定方式。AngularJS指令中的数据绑定的两种方式

下面是从模板我的HTML代码,一个基本的控制器实例为MyModel(这里的数组)使用:

HTML

<select ng-if="mymodel" multipleselect values="mymodel"> 

DIRECTIVE

我有一个指令称为multipleselect:

return { 
    restrict: 'A', 
    scope : { 
    values : '=' 
    }, 
    link : function($scope, element, attrs){ 

    ... 
    $scope.values = ["some","nice","datas"]; //Actually works, the model is changed in the controller 

    $("select").change(function(){ //This is a callback, asynchronous situation 
     $scope.$apply(function() { //Using apply to notify the controller that we are changing its model 
      $scope.values = ["some","amazing","datas"]; //Not working :(
     }); 
    }); 
    } 
} 

为什么我的模型没有更新第二个tim我改变它了吗?

+0

你在哪里定义'mymodel'财产?由于您在指令中使用了双向绑定,因此应该在'multipleselect'指令的封闭/父元素范围内定义'mymodel'属性。 – Arkantos

+0

我过去用'ng-if'和类似的东西出现了问题,它会从DOM中删除实际的元素并将其替换。不知道它是否可能是一个类似的问题。也只是为了让您知道您的更改会针对页面上的每个选项启动。您应该使用元素对象来将您的事件范围限定为指令。你也应该听取销毁事件,以便在“ng-if”中删除处理程序时移除该处理程序。可能导致内存泄漏。 – ste2425

回答

2

看着给,我认为这将满足您的需求,而无需使用自定义指令答案:

<select ng-if="mymodel" multiple ng-model="model.mymodel"> 

你的模式将当选择改变时可以自动更新,可以看到here

的egghead.io视频"The Dot"有一个很好的概述,做到这一点非常流行的堆栈溢出问题:What are the nuances of scope prototypal/prototypical inheritance in AngularJS?

+0

@ ste2425使用ng时应该总是使用'.'符号-model,看到这个小提琴:https://jsfiddle.net/vewk68xt/2/ –

+0

编辑:对不起,是我的坏被愚蠢, – ste2425

+0

@ ste2425检查我的回应 –

0

您不需要使用jQuery来监视更改。你可以写这样的(也解决您的问题):

return { 
    restrict: 'A', 
    scope : { 
    values : '=' 
    }, 
    link : function($scope, element, attrs){ 

    $scope.values = ["some","nice","datas"]; 

    element.on("change", function(){ 
     $scope.values = ["some","amazing","datas"]; 
    }); 
    } 
} 
+0

元素是一个jQuery(或jQLite,如果jQuery不包含在angular之前的)对象的指令。 – ste2425

+0

为什么不使用ng-change? –

+1

@MartijnWelker,因为该指令没有指定模板。您将不得不手动编译html以添加“ng-change”的绑定。 – ste2425

相关问题