Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch function in directive not getting triggered in Angular JS

I'm new to angular js and have been looking everywhere for an answer to why this isn't working.

I have my directive here:

.directive('carrouselPreview', function () {
    return function (scope, element, attrs) {
        scope.$watch(scope.carouselPreview, function () {
            alert('changed');
        }, true);
    }
});

This watches for a change to scope.carouselPreview, which is changed through this function:

$scope.showPreview = function(ind){
    $scope.carouselPreview = ind;
} 

This function definitely fires and changes scope.carouselPreview - but the watch function never fires!

I realise I'm probably being dumb here but I've looked all over and it seems perfectly fine.

If anyone helps me fix this tonight I'll love you forever!

like image 738
Tom Shorrock Avatar asked Nov 14 '12 18:11

Tom Shorrock


People also ask

What $apply in AngularJS?

In AngularJS, $apply() function is used to evaluate expressions outside of the AngularJS context (browser DOM Events, XHR). Moreover, $apply has $digest under its hood, which is ultimately called whenever $apply() is called to update the data bindings.

What is restrict in AngularJS directive?

Restrict. Angular allows us to set a property named restrict on the object we return on our directive definition. We can pass through a string with certain letters letting Angular know how our directive can be used. function MyDirective() { return { restrict: 'E', template: '<div>Hello world!


1 Answers

The first parameter into the $watch is a string (evaluated in the context of the scope) or a function. So what you want is:

scope.$watch("carouselPreview", function () {
    alert('changed');
}, true);

See http://docs.angularjs.org/api/ng.$rootScope.Scope#$watch

like image 191
dnc253 Avatar answered Nov 15 '22 17:11

dnc253