简体   繁体   English

AngularJS:带有监视链接的指令

[英]AngularJS : Directive with watch in link

I'm writing an angular directive that has a function called init() that needs to run when the page loads, and any time two variables change. 我正在编写一个角度指令,该指令具有一个名为init()的函数,该函数需要在页面加载时以及两个变量每次更改时运行。 I started out with this: 我从这个开始:

link: function(scope, elem, attrs){
    init();
    //Refresh the view when the the type or typeId changes
    scope.$watch("[type,typeId]", function(){init(scope)}, true);
},

But I noticed that init() was actually getting called twice. 但是我注意到init()实际上被调用了两次。 After I took the first init() out it obviously would only run once, but I'm just curious, is this expected behavior? 在我取出第一个init()之后,它显然只会运行一次,但是我很好奇,这是预期的行为吗?

I thought watch functions only execute when something changes. 我以为watch函数仅在发生变化时才执行。 Is it because they are technically "changing" (being initialized after link?) or is it just the natural behavior of $watch to immediately execute the function? 是因为它们在技术上正在“更改”(在链接之后初始化?)还是只是立即执行该函数的$ watch的自然行为?

$watch listeners are called when they are registered. $watch侦听器在注册时被调用。 If you don't want to execute the code inside of your listener function when you are initializing the watcher, then you can do something like this: 如果在初始化监视程序时不想在监听程序函数中执行代码,则可以执行以下操作:

scope.$watch("[type,typeId]", function(oldValue, newValue) {
    if (oldValue === newValue) return;

    // This code will only be hit when oldValue is different from newValue
    init(scope)
}, true);

appending to the accepted answer.. This even seems to be the "official" solution. 追加到已接受的答案。这甚至似乎是“官方”解决方案。

After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. 在范围内注册了监视程序后,将异步调用侦听器fn(通过$ evalAsync)以初始化监视程序。 In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. 在极少数情况下,这是不希望的,因为当watchExpression的结果未更改时会调用侦听器。 To detect this scenario within the listener fn, you can compare the newVal and oldVal. 要在侦听器fn中检测到这种情况,可以比较newVal和oldVal。 If these two values are identical (===) then the listener was called due to initialization. 如果这两个值相同(===),则由于初始化而调用了侦听器。

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

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

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