范围在角度上表现不同

时间:2016-04-12 08:39:37

标签: javascript angularjs

我试图理解角度范围。

<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的结果未按预期提供数据。为什么结果使用fn工作正常,可以看到fn执行3次。这背后的真正原因是什么。

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以使用 $ 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

答案 1 :(得分:0)

如果要实现此行为,则应在输入模型上使用$ scope。$ watch。

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

小提琴:https://jsfiddle.net/Lt7aP/2537/