简体   繁体   English

指令中的$ watch函数未在Angular JS中触发

[英]$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.carouselPreview的更改,该更改通过以下函数进行更改:

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

This function definitely fires and changes scope.carouselPreview - but the watch function never fires! 这个函数肯定会触发并更改scope.carouselPreview - 但是watch函数永远不会触发!

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! 如果今晚有人帮我解决这个问题,我会永远爱你!

The first parameter into the $watch is a string (evaluated in the context of the scope) or a function. $watch的第一个参数是字符串(在范围的上下文中计算)或函数。 So what you want is: 所以你想要的是:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM