【问题标题】:Multiple Controllers for one view angularjs一个视图的多个控制器
【发布时间】:2014-06-02 01:46:28
【问题描述】:

我想知道是否可以使用 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>

【问题讨论】:

标签: javascript angularjs controller


【解决方案1】:

是的,控制器和模板是独立的,检查这个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];
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多