摘要:MVVM基本架構
一般寫法:
<!DOCTYPE html>
<html ng-app="sampleApp">
<head>
<meta charset="utf-8">
<title>Lab 1 - 計算型屬性</title>
</head>
<body>
<div ng-controller="mainCtrl">
<input type="text" ng-model="firstName" />
<input type="text" ng-model="lastName" />
<br />
<span ng-bind="fullName()"></span>
<br />
<span>{{ fullName() }}</span>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<script>
angular.module("sampleApp", [])
.controller("mainCtrl", function($scope) {
$scope.firstName="Jeffrey";
$scope.lastName="Lee";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>
======進階寫法==================================================================
$scope.model = new myViewModel(),而ng-model則要改用model.firstName, model.lastName, model.fullName()
將ViewModel類別自$scope抽離,以便用程式產生器依文件或C#類別產生對應的ViewModel,在大型專案中有其必要性
<div ng-controller="mainCtrl">
<input type="text" ng-model="model.firstName" />
<input type="text" ng-model="model.lastName" />
<br />
<span ng-bind="model.fullName()"></span>
<br />
<span>{{ model.fullName() }}</span>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js"></script>
<script>
angular.module("sampleApp", [])
.controller("mainCtrl", function($scope) {
function myViewModel() {
var self = this;
self.firstName="Jeffrey";
self.lastName="Lee";
self.fullName = function() {
return self.firstName + " " + self.lastName;
};
}
$scope.model = new myViewModel();
});
</script>