Angularjs: Listen to model change in a directive

北慕城南 提交于 2019-12-14 00:43:05

问题


I'm trying to find out how I can listen to when the model is updated within an 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);
          });
        } 
      } 
    }
};

});

The directive is called within ng-repeat as

<div ng-repeat="ticket in tickets">
    <input my-amount ng-model="ticket.price"></input> 
</div>

Very happy for any help. I don't understand how the scope attribute looks like within an ng-repeat.

Thanks.


回答1:


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

attrs instead 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);
          });
        } 
      } ;
    }
);



回答2:


Try doing this

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);
          });
        } 
      } 
    }
  };
});



回答3:


eventEditor.directive('myAmount',function(){
return {
    restrict: 'A',
    required : 'ngModel'       // Add required property 
    link: function(scope, elem, attrs,ngModelCtr) {

      ngModelCtr.$render = function(){   //  Add $render 
      // Your logic
    }

  } 
 }
 };
 });
  1. Add a required property with ngModel, Since you are using ngModel (i mean actual angular ng-model, not the user custom ng-model attribute).
  2. Then call $render function. It will execute as soon as there is a change in ngModel (change in values of $modelValue and $viewValue). https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#$render

You can use $watch that is also correct.




回答4:


Following code works for me.

app.directive('myAmount',function(){
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
          attrs.$observe('ngModel', function (v) {
            console.log('value changed, new value is: ' + v);
          });
        } 
      } ;
    }
);


来源:https://stackoverflow.com/questions/25878189/angularjs-listen-to-model-change-in-a-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!