我有两个控制器。我想根据依赖值使用其他控制器。我无法在$ route级别进行设置。从本质上讲,我该如何在主控制器上执行此操作:甚至可能吗?
angular.module('app').controller('Controller1', ['importantService', function(importantService) {
if (importantService.getValue) {
// Use this other controller Controller2 instead
}
});
答案 0 :(得分:0)
您可以将2个控制器放入指令中,并在两者之间的模板切换中添加ng-if,例如:
app.controller('MainCtrl', function($scope, importantService) {
$scope.importantValue = importantService.getValue;
});
app.directive('myFirstComponent', function() {
return {
restrict: 'E',
templateUrl: '/same/url/for/both',
controller: function() {/*...your controller 1*/}
};
});
app.directive('mySecondComponent', function() {
return {
restrict: 'E',
templateUrl: '/same/url/for/both',
controller: function() {/*...your controller 2*/}
};
});
并在您的模板中
<div ng-if="importantValue === 1"><my-first-component></my-first-component></div>
<div ng-if="importantValue === 0"><my-second-component></my-second-component></div>
可能不是最正统的解决方案,但是它将满足您的要求。