Daniel
Daniel

Reputation: 1755

Why does not change value in directive Angular js?

I have simple directive in Angular JS:

 .directive("statusClass", function() {

        return {
            restrict: 'A',
            scope: {
                'status': '='
            },

            link: function(scope, element, attrs) {


                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;

                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }

            }
        }
    })

And call that like:

<div status-class status="data.active"></div>

Why when I change model outside: $scope.data.active = "go"; it is not bind with directive? So I can not see chnages in directive

Upvotes: 0

Views: 49

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

you need to use $watch to listen when the variable change and then fire the function.

Because link function gets executed at the run time. so when you are changing a directive scope variable it is not executed unless you fire an event(function for example).

 .directive("statusClass", function() {
    return {
        restrict: 'A',
        scope: {
            'status': '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('status', function() {
                switch (scope.status) {
                    case "pending":
                    case "Pending":
                        element.addClass('badge-default');
                        break;
                    case "completed":
                        element.addClass('badge-primary');
                        break;
                }
            })
        }
    }
})

Upvotes: 1

Related Questions