[英]AngularJS - linking Fn is evaluated many times in directive
'use strict'; angular.module('app', []) .controller('MainCtrl', function($scope) { console.log('heyo') }) .directive('panel', function() { return { template: '<div ng-if="isAuthenticated()">Im In!</div>', restrict: 'E', scope: {}, replace: true, link: function(scope, element, attrs) { var uid = 3 scope.isAuthenticated = function() { console.log(uid) return uid !== null } } } })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.4/angular.min.js"></script> <div ng-app="app"> <panel></panel> </div>
我的問題非常簡單明了。 在我的應用程序上, console.log
被評估了50次,而這里只有2次。
到底是怎么回事?
我認為它與$digest()
周期有關,即使不緊密相關,但更生動的答案將是不錯的選擇。
不是多次評估link
功能,而是每次$digest
進程運行時都會檢查isAuthenticated
方法(基本上在模型更改時進行檢查)。
您可以在此處看到http://plnkr.co/edit/3mHI2wxELwdF5Th2Pjhk?p=preview ,每次$scope.y
更改時,其評估值為isAuthenticated
ngIf在提供的表達式上調用$ watch函數,在您的情況下為“ isAuthenticated()”。
每次$ digest調用都會調用此表達式。 請參閱: https : //docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$ watch
在以上鏈接中,請注意:
在每次調用$ digest()時都會調用watchExpression,並且應返回將被監視的值。
但是也:
由於$ digest()在檢測到更改時會重新運行,因此watchExpression可以對每個$ digest()執行多次,並且應該是冪等的
在這里,您可以觀察ngClick如何調用摘要,從而生成ngIf評估表達式是否為http://jsfiddle.net/kihu/bbs8ajnk/2/
此行記錄摘要循環:
$rootScope.$watch(function(){console.log("digest")}, function(){console.log('looped')});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.