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

时间:2017-11-13 13:13:09

标签: javascript html angularjs variables ternary-operator

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

示例:

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

或:

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

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

3 个答案:

答案 0 :(得分:5)

在AngularJS中,将执行包括三元运算符在内的每个表达式:

  • 首次加载页面时。
  • 只要在角度应用ui.isTrue中更改了scope变量。

如果您查看angular scope documentation,特别是范围作为数据模型部分,您会看到:

  

Scope是应用程序控制器和视图之间的粘合剂。在模板链接阶段,指令在范围上设置$watch表达式。

     

$watch允许向指令通知属性   更改,允许指令将更新的值呈现给   DOM。

因此,当范围中的属性发生更改时,将始终通知视图,因此将自动评估三元表达式。

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

我自己做了一个小小的测试。

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

HTML:

$("#tax").validate({
  // Specify the validation rules
  rules: {
    igst: {
      digits: true,
      max: 2
    }
  },
  // Specify the validation error messages
  messages: {
    igst: {
      digits: "Please enter a valid number.",
      max: "Please enter a value less than or equal to 2."
    }
  },
  submitHandler: function(form) {
    form.submit();
  }
});

JS:

<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>

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

编辑: 使用它可以轻松创建无限的摘要循环。一旦在三元运算符调用的函数中$ scope中的某些内容将被更改,将启动另一个摘要,它将再次执行三元运算符的功能等。

相关问题