AngularJS中controller控制器继承的使用方法(2)
以上,ParentCtrl中vm对象的被ChildCtrl分享,当然也分享了对象中的name字段,当改变ChildCtrl中的vm.name值会影响到ParentCtrl,也就是不会把ParentCtrl和ChildCtrl之间的嵌套关系打破。
嵌套控制器中方法是如何被继承的?
myApp.controller("ArrayCtrl", function($scope){
$scope.myArray = ["John", "Andrew"];
$scope.add = function(name){
$scope.myArray.push(name);
}
})
myApp.controller("CollectionCtrl", function($scope){
})
<div ng-controller="ArrayCtrl">
<label>My Array:</label><span>{{myArray}}</span>
<label>parent controller:</label>
<input ng-model="parentName" />
<button ng-click="add(parentName)">Add New Item</button>
<div ng-controller="CollectionCtrl">
<label>child controller:</label>
<input ng-model="childName" />
<input type="number" ng-model="index" />
<button ng-click="add(childName)">Add New Item</button>
</div>
</div>
使用ArrayCtrl中的add方法,添加没问题;而且ArrayCtrl中的add方法也可以被CollctionCtrl使用;
而且在子控制器中可以重写父控制器中的方法。
myApp.controller("CollectionCtrl", function($scope){
//插入到某个位置
$scope.add = function(name, index){
$scope.myArray.splice(index,0, name);
}
})
<div ng-controller="ArrayCtrl">
<label>My Array:</label><span>{{myArray}}</span>
<label>parent controller:</label>
<input ng-model="parentName" />
<button ng-click="add(parentName)">Add New Item</button>
<div ng-controller="CollectionCtrl">
<label>child controller:</label>
<input ng-model="childName" />
<input type="number" ng-model="index" />
<button ng-click="add(childName, index)">Add New Item</button>
</div>
</div>
代码案例
1.创建一个 base.controller.js 文件
(function() {
'use strict';
angular
.module('DemoApp')
.controller('BaseCtrl', BaseCtrl);
//手动注入一些服务
BaseCtrl.$inject = ['$scope','CRUDServices'];
/* @ngInject */
function BaseCtrl($scope,CRUDServices) {
var _this = this;
//当前 controller 提供一些方法
_this.bFormValid = formValid;
activate();
////////////////
//初始化时候调用
function activate() {
getList();
}
// 获取数据列表
function getList() {
//把当前的结果赋值给 bList 属性上
_this.bList = CRUDServices.getList();
}
// 表单验证
function formValid(){
//do some thing
return false;
}
}
})();
代码很简单,我们在 BaseController中提供了一个简单的 formValid() 方法,还初始化调用了一个getList() 方法。
