我想知道的是如何为单个页面应用程序使用多个 Controller 。我试图弄明白,我发现的问题与我的问题非常相似,但是对于解决特定问题的答案只有大量不同,在这种情况下,您最终不会为单个页面应用程序使用多个 Controller 。
那是因为在一个页面上使用多个 Controller 是不明智的吗?还是根本不可能?
假设我已经有一个很棒的图像轮播 Controller 在主页上运行,但后来我学习了如何(比方说)使用模态,我也需要一个新的 Controller (或者我需要的任何其他东西) Controller )。那我该怎么办?
我看到了一些其他问题的答案,他们问的问题与我几乎相同,人们回答“*天哪。你为什么要那样做,就这样做......”。
什么是最好的方法,或者你是怎么做到的?
编辑
你们中的许多人都回答只是声明两个 Controller ,然后使用 ng-controller 来调用它。 我在下面使用这段代码,然后使用 ng-controller 调用 MainCtrl。
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: "templates/main.html",
controller:'MainCtrl',
})
.otherwise({
template: 'does not exists'
});
});
如果我可以在没有它的情况下使用 ng-controller,为什么我什至需要在这里设置一个 Controller ?这就是让我困惑的地方。 (我认为你不能以这种方式添加两个 Controller ......)
最佳答案
问题是什么?要使用多个 Controller ,只需使用多个 ngController 指令:
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
像往常一样,您需要在应用程序模块中提供可用的 Controller 。
最基本的方法可以像这样声明 Controller 功能一样简单:
function widgetController($scope) {
// stuff here
}
function menuController($scope) {
// stuff here
}
关于javascript - 在单页应用程序中使用 AngularJS 的多个 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24316355/