Angular Directive refresh on parameter change

后端 未结 5 1177
不思量自难忘°
不思量自难忘° 2020-12-04 13:08

I have an angular directive which is initialized like so:

         


        
5条回答
  •  春和景丽
    2020-12-04 13:49

    What you're trying to do is to monitor the property of attribute in directive. You can watch the property of attribute changes using $observe() as follows:

    angular.module('myApp').directive('conversation', function() {
      return {
        restrict: 'E',
        replace: true,
        compile: function(tElement, attr) {
          attr.$observe('typeId', function(data) {
                console.log("Updated data ", data);
          }, true);
    
        }
      };
    });
    

    Keep in mind that I used the 'compile' function in the directive here because you haven't mentioned if you have any models and whether this is performance sensitive.

    If you have models, you need to change the 'compile' function to 'link' or use 'controller' and to monitor the property of a model changes, you should use $watch(), and take of the angular {{}} brackets from the property, example:

    
    

    And in the directive:

    angular.module('myApp').directive('conversation', function() {
      return {
        scope: {
          typeId: '=',
        },
        link: function(scope, elm, attr) {
    
          scope.$watch('typeId', function(newValue, oldValue) {
              if (newValue !== oldValue) {
                // You actions here
                console.log("I got the new value! ", newValue);
              }
          }, true);
    
        }
      };
    });
    

提交回复
热议问题