8

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!

1 Answer 1

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

dnc253 you are a hero sir! May the lord bless you with a thousand virgins, thank you so much.
Thank you. As a side comment. Notice the key phrase "evaluated in the context of the scope" so if you have an isolated scope property of "carouselPreview" it is not the string "scope.carouselPreview" that you use but just "carouselPreview" since scope is assumed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.