我试图理解角度范围。
<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次。这背后的真正原因是什么。
提前致谢
答案 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>
答案 1 :(得分:0)
如果要实现此行为,则应在输入模型上使用$ scope。$ watch。
$scope.$watch('number',function(newValue, oldValue){
if(typeof newValue!=='undefined' && newValue!==oldValue){
$scope.result = newValue * newValue;
}
})