AngularJS指令中的两种数据绑定方式

时间:2016-01-20 13:15:14

标签: angularjs angularjs-directive angularjs-scope

我无法通过AngularJS指令获得数据绑定的两种方式。

这是我的模板中的html代码,用于实例化mymodel的基本控制器(这里是一个数组):

HTML

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

指令

我有一个名为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 :(
        });
    });
   }
}

为什么我的模型第二次更改时没有更新?

2 个答案:

答案 0 :(得分: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?

答案 1 :(得分: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"];
    });
   }
}