范围在角度上表现不同
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/
相关文章:
- 正在全局范围中查找JavaScript函数
- 如何通过数组更新角度子范围
- 如何使用ngrepeat和双向绑定获得指令的隔离范围
- HTML范围:动态设置值属性
- "实例范围”;TypeScript类的getter/setter
- jquery日期选择器年份范围默认值
- Jpgraph:如何手动设置X轴和Y轴的范围
- 在对象数组中查找多个值的d3范围
- 动态加载angularjs并生成控制器和范围
- 如何通过谷歌应用程序脚本从谷歌文档中的位置确定命名范围
- 在Materialize Calendar中设置年份范围
- 在MVVM视图模型中处理应用程序范围的元素
- setInterval游戏循环的范围问题
- AngularJS获取范围中的选定项目
- 从指定范围创建字符数组
- ES6是否引入了一种机制来生成块范围的函数语句(而不是表达式)
- Angularjs无法将单选按钮与嵌套范围内的模型绑定
- ngDialog-弹出窗口未更新范围变量
- 如何使用D3生成特定范围内的随机颜色
- 如何将输入范围的值传递给JS中的变量