【问题标题】:Scope function calling on DOM change(two-way data binding) angularjs作用域函数调用 DOM 变化(双向数据绑定) angularjs
【发布时间】:2017-05-09 17:07:26
【问题描述】:
<!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>

在上面的代码中,isNumberA第一次调用是因为ng-if="isNumberA(10)",但我不知道为什么它会再次调用。检查控制台,它在浏览器中的 DOM 渲染上打印两次。之后,当我再次单击复选框时,它会调用该函数。为什么这个方法调用复选框单击?我没叫。这是双向绑定吗?而且,如果我删除&lt;h1 ng-if="isNumberA(10)"&gt;&lt;/h1&gt;,它也不会调用。这里发生了什么?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您使用了函数调用而不是条件变量 (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>
    

    【讨论】:

      【解决方案2】:

      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

      【讨论】:

      • 请详细说明你的答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多