在分配$ stateProvider.state多控制器控制器、分配、stateProvider、state

2023-09-14 00:11:54 作者:彩虹餹dē夢

也许这是为高级用户的角度一个简单的问题,但我没有找到这个问题的地方很好的解释。

Probably this is an easy question for advanced angular users, but I did not find this issue somewhere well explained.

所以,我调整我的code,当我意识到,我有一个观点,这不是一个问题,当控制器ACtrl是由$ stateProvider和控制器绑定两个控制器'BCtrl被绑定在吴控制器的看法。但是,当我尝试在$ stateProvider这样分配他们两个:

So I was restructuring my code, when I realized, I have two controllers in a view, which is not a problem, when controller 'ACtrl' is binded by the $stateProvider and controller 'BCtrl' is binded in the view by ng-controller. But when I try to assign both of them in the $stateProvider like this:

$stateProvider.state('a.view', {
    url: "/anurl",
    views: {
        'menuContent': {
            templateUrl: "anUrlToMyTemplates",
            controller: 'ACtrl', 'BCtrl'
        }
    }
}); 

$stateProvider.state('a.view', {
    url: "/anurl",
    views: {
        'menuContent': {
            templateUrl: "anUrlToMyTemplates",
            controller: 'ACtrl',
            controller: 'BCtrl'
        }
    }
});

这是行不通的。

我知道这将是使控制器的最多一个内容的解决方案,但控制器ACtrl'用于别的地方也一样,所以我不得不重复自己别的地方。我怎样才能解决这个问题...

I know it would be a solution to make the content of the controllers up to one, but controller 'ACtrl' is used somewhere else, too, so I would have to repeat myself somewhere else. How can I solve this...

推荐答案

Syntaxically,它不能正常工作。这(syntaxically)可以工作:

Syntaxically, it can't work. This (syntaxically) could work :

$stateProvider.state('a.view', {
    url: "/anurl",
    views: {
        'menuContent': {
            templateUrl: "anUrlToMyTemplates",
            controller: ['ACtrl', 'BCtrl']
        }
    }
}); 

但AngularJS使用 ZERO 或 ONE 控制器通过一个DOMElement

您可以指定 CTRLA A 查看:

$stateProvider.state('a.view', {
    url: "/anurl",
    views: {
        'menuContent': {
            templateUrl: "anUrlToMyTemplates",
            controller: 'ACtrl'
        }
    }
}); 

和和到您 A 查看:

<div data-ng-controller="BCtrl">
    <!-- your view content -->
</div>

这是说,为code设计的目的,正确的做法是要合并的两个控制器的动作只有一个,如果他们要控制相同的模板元素。如果它们控制的模板的不同部分,使用一个部分的特定部分的一个控制器,或为整个视图的控制器,和一个其他

That said, for code design purpose, the correct way is to merge the actions of your two controllers in only one if they have to control the same template elements. If they control different parts of the template, use one controller for one part, or a controller for the whole view, and an other for the specific part :

<!-- your view controlled by ACtrl configured in route provider -->
<div> 
    <!-- your view content, part A -->

    <div data-ng-controller="BCtrl">
        <!-- your view content, part B -->
    </div>
</div>
 
精彩推荐