本篇主要介紹控制器的$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"是無效的表示式.