三元运算符会在每个摘要上执行吗?

Will the ternary operator be executed on every digest?

如果我在 Angular.js 视图中使用三元运算符,它会在每个摘要(如函数)上执行还是仅在决策所需的变量发生更改时执行?

示例:

<div>{{ui.isTrue ? "foo" : "bar"}}</div>

或:

<div ng-bind="ui.isTrue ? 'foo' : 'bar'"></div>

它会在每个摘要上执行还是仅在 ui.IsTrue 更改时执行?

在AngularJS中,包括三元运算符在内的所有表达式都会被执行:

  • 首先在页面加载时。
  • 并且每当 angular 应用中的 ui.isTrue 变量发生变化时 scope

如果您查看 angular scope documentation,特别是 Scope as Data-Model 部分,您将看到:

Scope is the glue between application controller and the view. During the template linking phase the directives set up $watch expressions on the scope.

The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.

所以当作用域中的属性发生变化时,视图总是会得到通知,所以三元表达式会自动求值。

这是您正在查看的示例,是的它将在每个摘要中执行

var app = angular.module('myApp', []);
app.controller('MyController', ['$scope', MyController]);
function MyController($scope) {
 $scope.isTrue = true;
    setInterval(function() {
      $scope.isTrue = !$scope.isTrue;
      $scope.$digest();
  }, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<div ng-app="myApp" ng-controller='MyController'>
    <div>{{isTrue ? "foo" : "bar"}}</div>
</div>

了解 Digest

我做了一个 fiddle 来自己测试。

http://jsfiddle.net/xuvzzay8/4/

HTML:

<div ng-controller="MyCtrl">    
    {{bool ? ternaryTrue() : ternaryFalse() }}<br/>

    {{bool}}<br/>        
    <button ng-click="bool = !bool">Toggle Bool</button>
    {{a}}
    <div style="background-color:red" ng-mouseover="hover()">
        Hover here to trigger digest
    </div>
</div>

JS:

var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {    
    $scope.bool = true; 
    $scope.a = 0;
    $scope.ternaryTrue = function(){
        console.log("ternary executed on true");   
    }
    $scope.ternaryFalse = function(){
        $scope.a++; //creates an infinite digest loop
        console.log("ternary executed on false");   
    }    
    $scope.hover = function(){
        console.log("Hover");
    }
}

结果是对每个摘要执行三元运算符。

编辑: 可以很容易地创建一个无限摘要循环。一旦 $scope 中的某些内容在三元运算符调用的函数期间发生更改,将启动另一个摘要,再次执行三元运算符的函数等。