Angualr.js-从一个控制器重定向到另一个

时间:2018-12-14 21:22:34

标签: angularjs

我有两个控制器。我想根据依赖值使用其他控制器。我无法在$ route级别进行设置。从本质上讲,我该如何在主控制器上执行此操作:甚至可能吗?

angular.module('app').controller('Controller1', ['importantService', function(importantService) {

    if (importantService.getValue) {
       // Use this other controller Controller2 instead
    }

});

1 个答案:

答案 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>

可能不是最正统的解决方案,但是它将满足您的要求。

相关问题