调用DOM更改(双向数据绑定)angularjs的作用域函数

时间:2016-12-24 06:12:50

标签: javascript angularjs

<!DOCTYPE html>
<html data-ng-app="app">

<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>

<body data-ng-controller="SimpleController">
  <script>
    var app = angular.module('app', []);
    app.controller('SimpleController', SimpleController);

    function SimpleController($scope) {
      $scope.isNumberA = function(val) {
        console.log('called');
        if (val == 2) return true;
      }
    }
  </script>
  <input type="checkbox" ng-model="switcher" />
  <h1 ng-if="isNumberA(10)">isNumber</h1>

</body>

</html>

在上面的代码第一次,isNumberAng-if="isNumberA(10)"而致电,但我不知道为什么要再次呼叫。检查控制台,它在浏览器的DOM渲染上打印两次。之后,当我再次单击复选框时,它会调用该函数。为什么这个方法调用复选框单击?我没有打电话给它。这是双向约束吗?而且如果我删除<h1 ng-if="isNumberA(10)"></h1>,它就不会调用。这里发生了什么?

2 个答案:

答案 0 :(得分:2)

您已使用函数调用而不是条件变量(ng-if)。 Angular监视视图中使用的每个范围变量,但是当您使用函数调用时,它无法确定哪个变量或事件会影响此函数的返回值,因此Angular在每个摘要周期运行此类函数。 您应该在ng-init中调用此函数并将此函数的返回值存储在变量中,并在ng-if中使用该函数。

$scope.isNumberA = function(val) {
    console.log('called');
    if (val == 2){
        $scope.showIfBlock = true;
    } else {
        $scope.showIfBlock = false;
    }
  }


<span ng-init="isNumberA(10)"></sapn>
<h1 ng-if="showIfBlock">isNumber</h1>

答案 1 :(得分:1)

ng-if会在摘要周期运行时评估其表达式,基本上你不应该从ng-if表达式进行函数调用。

<强>样本

<!DOCTYPE html>
<html data-ng-app="app">
<head>
  <title></title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body data-ng-controller="SimpleController">
  <script>
    var app = angular.module('app', []);
    app.controller('SimpleController', SimpleController);
    function SimpleController($scope) {
      $scope.isNumberA = function(val) {
        console.log('called');
        if (val == 2) $scope.block = true;
        $scope.block = false;
      }
    }
  </script>
  <input type="checkbox" ng-model="switcher" />
  <span ng-init="isNumberA(10)"></sapn>
   <h1 ng-if="block">isNumber</h1> 
</body>
</html>

在这里阅读更多

ng-if being called more times than it should