How to watch property in attrs of directive

后端 未结 5 1490
难免孤独
难免孤独 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:29

    I had to implement this myself and found a solution! Unfortunately, when I tried .$watch, errors were just spewing out on the console. So I used $observe instead.

    Here's my solution:

    angular.module('app').directive('aDate', [
        function() {
            return {
                template: '{{date}}',
                restrict: 'E',
                replace: true,
                link: function(scope, element, attrs) {
                    attrs.$observe('date', function (val) {
                        var d = new Date(val);
                        element.text(d);
                    });
                }
            };
        }
    ]);
    

    The above code changes the scoped date when the date attribute of the element changes!

    Cheers!

提交回复
热议问题