How to watch property in attrs of directive

后端 未结 5 1482
难免孤独
难免孤独 2020-12-25 14:44

I have a controller that has a counter that changes from time to time.
That counter is tied to an attribute of a directive and read inside the link function of that dire

5条回答
  •  攒了一身酷
    2020-12-25 15:20

    Use attrs.$observe(key, fn). More info at $compile.directive.Attributes

    attrs.$observe('counter',function(counter){
    
    });
    

    Related answer: https://stackoverflow.com/a/14907826/2874153

    $observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s). E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...). (If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

提交回复
热议问题