Piotr Łużecki
Piotr Łużecki

Reputation: 1041

Angularjs directive watching binded attributes

I need to create simple directive which will show some value if another value change. For example it will watch for 'event' and if event.eventDuration === 'Now' then it have to change it's value to 'Surprise!'.

With my code I see valid event in the console only once. If I do some changes only {{event.eventDuration}} changes, not my directive. What I did wrong?

In the html code where it is used I have this:

    <event-time event="event"></event-time>{{event.eventDuration}}

This is my custom directive:

angular.module('my-app').directive('eventTime', function ($c, $compile) {
    var linker = function(scope, element, attrs) {
        scope.$watch('event', function(newValue){
            if (newValue !== undefined && newValue.eventDuration !== undefined) {
                scope.value = newValue.eventDuration;
                element.html(scope.value);
                $compile(element.contents())(scope);
            }
        });
    };

    return {
        restrict: 'E',
        template: '{{value}}',
        transclude: true,
        scope: {
            'event': '='
        },
        link: linker,
        controller: function ($scope) {
            //init value
            $scope.value = 'x';
        }
    };
});

Upvotes: 0

Views: 75

Answers (1)

New Dev
New Dev

Reputation: 49610

You can $watch an expression, like so:

scope.$watch("event.eventDuration", function(v){
   if (v === "Now"){
      // do whatever you need to display "Surprise!"
   }
});

It's not clear from your question where the "Surprise!" string should be rendered. If it's just the scope.value that you display in the template, then you don't need to $compile anything. Simply assign $scope.value = "Surprise!".

Upvotes: 1

Related Questions