0

我有一個關於如何在AngularJS中只有一個輸入文本框時避免觀察者的問題。Angular和Watchers中的單向或一次性綁定

我創建plunker它:plunker link : OneWay Binding using ng-value

這表明,即使當我使用NG-值只讀輸入文本,還是一個觀察者已經加入了它。

我簡單的想避免看守人有隻讀控件時,我這樣問是因爲在我的企業應用程序中,即使是隻讀頁面,我也有超過200個只讀控件和看守計數,正在減速到1100左右我的角度應用程序。

請讓我知道在這裏解決

感謝 如是

+0

也許試試這個:https://docs.angularjs.org/api/ng/directive/ng只是通過執行'ng-readonly = true'來查看是否有爲該值添加的觀察者。 – FlorianTopf

+0

感謝但沒有運氣,通過使ng-readonly = true不減少觀察者數量。 –

+0

單向綁定和一次性綁定有很大的區別。你想只更新一次視圖,還是隻想要一個只顯示模型值的只讀元素? – tasseKATT

回答

0

發現了一種具有單向綁定做到這一點:

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,因爲第二個輸入上的一次綁定在得到一個值時被評估,然後它移除了它的觀察者。