Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/398.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS:带有watch-in-link的指令_Javascript_Angularjs_Angularjs Directive_Watch - Fatal编程技术网

Javascript AngularJS:带有watch-in-link的指令

Javascript AngularJS:带有watch-in-link的指令,javascript,angularjs,angularjs-directive,watch,Javascript,Angularjs,Angularjs Directive,Watch,我正在编写一个angular指令,它有一个名为init()的函数,需要在页面加载时运行,并且在两个变量发生变化时随时运行。我从这个开始: link: function(scope, elem, attrs){ init(); //Refresh the view when the the type or typeId changes scope.$watch("[type,typeId]", function(){init(scope)}, true); }, 但我注意

我正在编写一个angular指令,它有一个名为init()的函数,需要在页面加载时运行,并且在两个变量发生变化时随时运行。我从这个开始:

link: function(scope, elem, attrs){
    init();
    //Refresh the view when the the type or typeId changes
    scope.$watch("[type,typeId]", function(){init(scope)}, true);
},
但我注意到init()实际上被调用了两次。在我取出第一个init()之后,它显然只运行一次,但我只是好奇,这是预期的行为吗


我认为手表功能只有在某些事情发生变化时才会执行。这是因为它们在技术上正在“更改”(在链接后初始化?),还是$watch立即执行该函数只是自然行为?

注册时调用$watch
侦听器。如果您不想在初始化监视程序时执行侦听器函数内部的代码,则可以执行以下操作:

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);

$watch
侦听器在注册时被调用。如果您不想在初始化监视程序时执行侦听器函数内部的代码,则可以执行以下操作:

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);

附在已接受的答案之后。。这甚至似乎是“官方”的解决方案

在向作用域注册观察程序后,异步调用侦听器fn(通过$evalAsync)来初始化观察程序。在极少数情况下,这是不可取的,因为在watchExpression的结果没有更改时调用侦听器。要在侦听器fn中检测此场景,可以比较newVal和oldVal。如果这两个值相同(==),则由于初始化而调用了侦听器


附加在已接受的答案之后。。这甚至似乎是“官方”的解决方案

在向作用域注册观察程序后,异步调用侦听器fn(通过$evalAsync)来初始化观察程序。在极少数情况下,这是不可取的,因为在watchExpression的结果没有更改时调用侦听器。要在侦听器fn中检测此场景,可以比较newVal和oldVal。如果这两个值相同(==),则由于初始化而调用了侦听器


好的,很高兴知道。不管怎样,在这种情况下,它实际上是可行的。谢谢好的,很高兴知道。不管怎样,在这种情况下,它实际上是可行的。谢谢谢谢你的额外投入!谢谢你的额外投入!