代码之家  ›  专栏  ›  技术社区  ›  KingKongFrog

Angualrjs-从一个控制器重定向到另一个控制器

  •  0
  • KingKongFrog  · 技术社区  · 6 年前

    我有两个控制器。我想使用另一个基于依赖值的控制器。我无法将此设置为$route级别。我怎样才能在主控制器中实现这一点:这甚至是可能的吗?

    angular.module('app').controller('Controller1', ['importantService', function(importantService) {
    
        if (importantService.getValue) {
           // Use this other controller Controller2 instead
        }
    
    });
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   ruedamanuel    6 年前

    您可以将两个控制器放入指令中,如果在模板中在这两个控制器之间切换,则会有一个ng,例如:

    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>
    

    可能不是最正统的解决方案,但它会按你的要求做。