一个视图angularjs的多个控制器

时间:2014-04-17 16:54:11

标签: javascript angularjs controller

我想知道是否可以使用angluarjs为单个url视图使用多个控制器,我还没有找到很多关于此的文档。我想在所有页面上使用控制器来切换页眉标题,但有些页面已经包含控制器

app.js

subscriptionApp.config(['$routeProvider',function($routeProvider){
$routeProvider.
when('/billinginfo',{templateUrl:'views/billing-info.html', controller:'billingInfoController'}).
when('/orderreview',{templateUrl:'views/order-review.html', controller:'billingInfoController'}).
when('/subscribed',{templateUrl:'views/subscribed.html', controller:'subscribedTitle'}).

//EXAMPLE: HOW COULD I ADD TWO CONTROLLERS TO SAME PAGE??? THIS DOES NOT WORK
when('/subscribe',{templateUrl:'views/subscribe.html', controller:'subscriptionController', 'testControllerTitle'}).

when('/unsubscribed',{templateUrl:'views/cancelconfirm.html', controller:'unsubscribedTitle'}).
when('/redirectBack',{templateUrl:'views/redirect-to-app.html'}).
when('/redirectHandler',{templateUrl:'views/redirect-handler.html',controller:'redirectController'}).
when('/error',{templateUrl:'views/error.html', controller:'messageController'}).
otherwise({redirectTo:'/subscribe'});
}]);

修改 我正在尝试为每个页面视图添加一个标题控制器:

function testControllerTitle($rootScope, $scope, $http) { $rootScope.header = "Success!"; }

如果我将这些控制器添加到尚未安装控制器的页面,那么如果有另一个控制器,我就无法完成这项工作。

<h1 ng-bind="header"></h1>

1 个答案:

答案 0 :(得分:4)

是的,控制器和模板是独立的,请查看http://jsbin.com/wijokuca/1/

var app = angular.module("App", ['ngRoute']);

app.config( function ( $routeProvider ) {
  $routeProvider
  .when('/a', {templateUrl: 'this.html', controller: "aCtrl"})
  .when('/b', {templateUrl: 'this.html', controller: "bCtrl"})
  .when('/c', {templateUrl: 'that.html', controller: "bCtrl"})
  .otherwise({redirectTo: '/a'});
});

app.controller('aCtrl', function ($scope) {
    $scope.all = [1,2,3];
});

app.controller('bCtrl', function ($scope) {
    $scope.all = [4,5,6];
});