使用routeParams时,为一页使用多个控制器?

时间:2016-01-13 08:54:06

标签: javascript angularjs html5

我在代码中使用routeParams时遇到问题。

第1版(工作正常)

的index.html

<div ng-controller="NaomiController">
      <my-customer></my-customer>
    </div>
    <hr>
    <div ng-controller="IgorController">
      <my-customer></my-customer>
    </div>

我的controller.js是:

    angular.module('docsScopeProblemExample', [])
    .controller('NaomiController', ['$scope', function($scope) {
      $scope.customer = {
        name: 'Naomi',
        address: '1600 Amphitheatre'
id:'na'
      };
    }])
    .controller('IgorController', ['$scope', function($scope) {
      $scope.customer = {

        name: 'Igor',
        address: '123 Somewhere'
id:'ig'
      };
    }])
    .directive('myCustomer', function() {
      return {
        restrict: 'E',
        templateUrl: 'my-customer.html'
      };
    });

和我的

my-customer.html是:

Name:<a href="{{customer.id}}">{{customer.name}}</a> , Address: {{customer.address}}

之后我想将routeParams用于下一页..

第二版代码(它不能正常工作)

所以index.html是:

<div ng-view></div>

app.js是:

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

App.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/', {
        template: 'home.html',
        controller: 'IgorController','NaomiController'
      }).
      when('/home/:id', {
        templateUrl: 'partials/detail.html',
        controller: 'detailCtrl'
      }).
      otherwise({
        redirectTo: '/home'
      });
  }]);

我的controller.js是:

    myControllers.controller('NaomiController', ['$scope', function($scope) {
              $scope.customer = {
                name: 'Naomi',
                address: '1600 Amphitheatre'
        id:'na'
              };
            }])
            .controller('IgorController', ['$scope', function($scope) {
              $scope.customer = {

                name: 'Igor',
                address: '123 Somewhere'
        id:'ig'
              };
            }])
            .directive('myCustomer', function() {
              return {
                restrict: 'E',
                templateUrl: 'my-customer.html'
              };
            }).controller('detailCtrl',['$scope', function($scope){
             $scope.message: "Hello"
}])

其中home.html包含:

<div ng-controller="NaomiController">
          <my-customer></my-customer>
        </div>
        <hr>
        <div ng-controller="IgorController">
          <my-customer></my-customer>
        </div>

和detail.html有:

{{message}}

我的代码的第二版无效

1 个答案:

答案 0 :(得分:1)

$routeProvider

只能使用一个控制器

您可以做的是为您的视图使用单个控制器,并将视图的HTML本身中的2个控制器与ng-controller

相关联