gpt4 book ai didi

javascript - 如果在 Angular 1.3+ 中使用一次性绑定(bind),则指令中的观察者为零

转载 作者:行者123 更新时间:2023-11-28 19:01:13 24 4
gpt4 key购买 nike

我做了一个user-name此问题的指令

.directive('userName', function($http) {
return {
restrict: 'E',
scope: {
user: '='
},
replace: true,
template: '<div><span ng-bind="user.username"></span> <a ng-if="user.active">Add</a></div>',
};
});

当我使用用户属性 ( <user-name user="::user"></user-name> ) 的一次性绑定(bind)时,该指令使用最小数量的监视,这一点很重要。

我有很多问题。我创建了 this plunker 测试我的指令。

  1. 尽管 user 为什么在一次性绑定(bind)的情况下会有观察者不会更新吗?
  2. 使用一次性绑定(bind)时,我可以将此指令中的观察者减少到零吗?
  3. 我已阅读documentation我需要在链接函数中使用 $watch 来更新 DOM - 这对我来说似乎不是这种情况。链接函数中什么时候需要$watch?

最佳答案

getWatchers 函数不会为观察者提供有意义的反馈(从范围中总结观察者也没有多大意义)。您可以尝试使用 $$postDigest 来监控此类事情。

无论如何,在链接指令后记录指令的范围 will give better feedback instantly .

如图所示,有三个观察者:

{isolateScope: Array[2], scope: Array[1]}

其中两个是user.usernameuser.active:

<div><span ng-bind="user.username"></span> <a ng-if="user.active">Add</a></div>

最后一个是{{$index}}:

<li ng-repeat="user in users" id="user_a_{{$index}}">

一次性将它们全部制作出来,并且应该为零。

When is $watch necessary in the link function?

正如所说,当更新监视范围属性时,必须更新 DOM 中没有数据绑定(bind)的内容。

与绑定(bind)相比,$watch 提供了很好的控制能力,例如一次性观察者的秘诀是

  var unwatch = scope.$watch('oneTime', function (newVal, oldVal) {
unwatch();
...
});

并且可以将其更改为“定义变量后立即停止监视”之类的内容。

它还可以用于观看范围之外的东西

scope.$watch(function () { return globalVar }, function () { scope.scopeVar = ... });

关于javascript - 如果在 Angular 1.3+ 中使用一次性绑定(bind),则指令中的观察者为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501943/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com