AngularJS的MVC架构更像是MVVM(Model,View,ViewModel)架构,控制器更像是ViewModel组件。
前面我们已经实现了模块调用controller()方法就可一次注册一个控制器,传入的第二参数是一个函数,在该函数中可以声明一个$scope形参,这个就是应用程式的模型(model),设定$scope对象的属性,该属性和HTML中ng-model对应的变量就双向绑定了。
下面我们看段代码,一个模块多个控制器
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<body>
<div ng-app="myApp" >
<div ng-controller="Ctrl_01" >
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
姓名: {{firstName + " " + lastName}}
</div>
<br/>
<div ng-controller="Ctrl_02" >
名: <input type="text" ng-model="firstName"><br>
姓: <input type="text" ng-model="lastName"><br>
姓名: {{firstName + " " + lastName}}
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl_01', fun1);
function fun1($scope){
$scope.firstName = "wh";
$scope.lastName = "zhang";
};
app.controller('Ctrl_02', function($scope) {
$scope.firstName = "ximi";
$scope.lastName = "han";
});
</script>
</body>
</html>