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!
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.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With