發現了一種具有單向綁定做到這一點:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
//$scope.watcherCount = 0;
$scope.countWatchers = function() {
var root = angular.element(document).injector().get('$rootScope');
var count = root.$$watchers ? root.$$watchers.length : 0; // include the current scope
var pendingChildHeads = [root.$$childHead];
var currentScope;
while (pendingChildHeads.length) {
currentScope = pendingChildHeads.shift();
while (currentScope) {
count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;
pendingChildHeads.push(currentScope.$$childHead);
currentScope = currentScope.$$nextSibling;
}
}
$scope.watcherCount = count;
// alert("there are " + count + " watchers");
return count;
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" ng-model="a">
<input type="text" value="{{::a}}" ng-readonly=true></input>
<button ng-click="countWatchers()">Get Watchers</button>
<br>
Watcher Count <!--table><tr></tab><td bo-text="watcherCount"></td></tr></table-->
<span>{{watcherCount}}</span>
</body>
</html>
嘗試按下「獲取看守」和看到觀察者計數最初是3.然後寫一些東西或複製/粘貼到第一個輸入並再次按下「獲得觀察者」。觀察者計數減少到2,因爲第二個輸入上的一次綁定在得到一個值時被評估,然後它移除了它的觀察者。
也許試試這個:https://docs.angularjs.org/api/ng/directive/ng只是通過執行'ng-readonly = true'來查看是否有爲該值添加的觀察者。 – FlorianTopf
感謝但沒有運氣,通過使ng-readonly = true不減少觀察者數量。 –
單向綁定和一次性綁定有很大的區別。你想只更新一次視圖,還是隻想要一個只顯示模型值的只讀元素? – tasseKATT