本篇主要介绍控制器的$scope中的数据是如何被改变的:
以下三种方法,都可以改变$scope中的number值:
1. 表达式:
<span ng-click="number=number+3">点击改变值1</span>
2. 回调函数:
<span ng-click="computeNum()">点击改变值2</span>
$scope.computeNum = function(){
$scope.number = $scope.number+3
}
3. input元素的ng-model属性:
<input type="text" ng-model="number"/>
完整代码:
<!DOCTYPE html> <html ng-app> <head> <title>10.1$scope数据控制</title> <meta charset="utf-8"> <script src="../angular.js"></script> <script src="script.js"></script> </head> <body> <div ng-controller = "ScopeData"> <span ng-click="number=number+3">点击改变值1</span> <br> <span ng-click="computeNum()">点击改变值2</span> <br> <span><input type="text" ng-model="number"/></span> <p>{{number}}</p> </div> </body> </html>
function ScopeData ($scope){ $scope.number = 0; $scope.computeNum = function(){ $scope.number = $scope.number+3 } }
可以看到,这三种方法都可以动态实时的改变$scope中number的值,其中,1和2是等价的.
*注意,在表达式里直接写ng-click="number-3"是无效的表达式.