我想知道某种类型的控制器有多少(我不是指Initialized
,我的意思是Exist
)
我认为这应该很容易,我错过了一些东西。
例如:
<body ng-app="waitfor">
<div ng-controller="oneof">
{{cindex}} {{last}}
</div>
<div ng-controller="oneof">
{{cindex}} {{last}}
</div>
<div ng-controller="oneof">
{{cindex}} {{last}}
</div>
</body>
我想知道存在3个oneof
个控制器,所以当最后一个控制器初始化时,我可以采取相应的行动。
答案 0 :(得分:0)
您需要什么:
跟踪现有控制器并公开注册/取消注册控制器实例的方法的服务。
一个控制器,它使用该服务在实例化时注册自己,并在销毁后取消注册。
示例实施:
1。)服务:
.factory('OneOfManyManager', function () {
/* Internal list of existing controller
* (i.e. instantated and not destroyed) */
var ctrls = [];
/* Returns the current count of existing controllers */
function getCount() {
return ctrls.length;
}
/* Registers a controller instance and returns its index
* (NOTE: With this implementation, indices are not necessarily unique) */
function register(ctrl) {
var idx = ctrls.length;
ctrls.push(ctrl);
return idx;
}
/* Unregisters a controller (if already registered)
* Return true upon successful unregistration of false otherwise */
function unregister(ctrl) {
var idx = ctrls.indexOf(ctrl);
ctrls.splice(idx, 1);
return idx !== -1;
}
/* The returned service object */
return {
getCount: getCount,
register: register,
unregister: unregister
};
});
2。)控制器:
.controller('oneOfManyCtrl', function ($scope, OneOfManyManager) {
var thisCtrl = this;
/* Register the controller upon instantition */
$scope.index = OneOfManyManager.register(thisCtrl);
$scope.getCount = OneOfManyManager.getCount;
/* Unregister the controller once upon destruction */
$scope.$on('$destroy', function (evt) {
var success = OneOfManyManager.unregister(thisCtrl);
if (success) {
console.log('Successfully unregistered controller:', thisCtrl);
console.log('Controllers left: ' + OneOfManyManager.getCount());
} else {
console.warn('WARNING: The controller wasn\'t registered !', thisCtrl);
}
});
});
另请参阅此 short demo 。