范围在角度上表现不同

scope behaving differently in angular

本文关键字:范围      更新时间:2024-05-02

我正在尝试理解角度中的范围。

<html>
   <head>
      <title>Angular JS Services</title>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>
   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "TestController">
         <p>Enter a number: <input type = "number" ng-model = "number" /></p>
         <p>Result using fn: {{resultData()}}</p>
         <p>Result using var: {{result}}</p>
      </div>
      <script>
         var mainApp = angular.module("mainApp", []);
         mainApp.controller('TestController', function($scope) {
             $scope.result = $scope.number * $scope.number;
             $scope.resultData = function(){ 
                 console.log("test");
                 return $scope.number *$scope.number;
             }
         });
      </script>
   </body>
</html>

这里,使用var的Result并没有给出预期的数据。为什么使用fn的Result工作正常,可以看到fn执行了3次。这背后的真正原因是什么。

提前感谢

因为Angular在每个摘要周期中计算模板变量。基本上,它会在每次作用域更改时再次尝试填充模板表达式,直到作用域上的变量稳定为止。

您可以使用$watch:

<html>
   <head>
      <title>Angular JS Services</title>
      <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
   </head>
   <body>
      <h2>AngularJS Sample Application</h2>
      <div ng-app = "mainApp" ng-controller = "TestController">
         <p>Enter a number: <input type = "number" ng-model = "number" /></p>
         <p>Result using fn: {{resultData()}}</p>
         <p>Result using var: {{result}}</p>
      </div>
      <script>
         var mainApp = angular.module("mainApp", []);
         mainApp.controller('TestController', function($scope) {
             $scope.$watch('number', function(val){
                 $scope.result = val * val;
             });
             $scope.resultData = function(){ 
                 console.log("test");
                 return $scope.number *$scope.number;
             }
         });
      </script>
   </body>
</html>

JSFiddle

当创建控制器时,使用var的结果是试图计算乘积,而此时数字尚未定义。

如果你想实现这种行为,你应该使用$scope$注意输入模型。

$scope.$watch('number',function(newValue, oldValue){
    if(typeof newValue!=='undefined' && newValue!==oldValue){
        $scope.result = newValue * newValue;
    }
})

Fiddle:https://jsfiddle.net/Lt7aP/2537/