Angularjs:在指令中听取模型变化

Nic*_*las 13 angularjs angularjs-directive

我试图找出在指令中更新模型时如何收听.

eventEditor.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          scope.$watch(attr['ngModel'], function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } 
    }
};
Run Code Online (Sandbox Code Playgroud)

});

该指令在ng-repeat中被调用为

<div ng-repeat="ticket in tickets">
    <input my-amount ng-model="ticket.price"></input> 
</div>
Run Code Online (Sandbox Code Playgroud)

非常高兴任何帮助.我不明白范围属性在ng-repeat中是怎样的.

谢谢.

syl*_*ter 21

http://jsbin.com/mihupo/1/edit

attrs 代替 attr

app.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          scope.$watch(attrs['ngModel'], function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } ;
    }
);
Run Code Online (Sandbox Code Playgroud)


az7*_*7ar 6

试试这个

eventEditor.directive('myAmount',function(){
    return {
    restrict: 'A',
    scope: {model: '=ngModel'},
    link: function(scope, elem, attrs) {
            scope.$watch('model', function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } 
    }
  };
});
Run Code Online (Sandbox Code Playgroud)