将多个控制器路由到同一视图和href

时间:2014-07-10 09:44:20

标签: javascript angularjs

我有一个页面,当用户点击链接检索总数据时,我想加载三个控制器,我希望总数据视图加载三个控制器。 到目前为止我已经完成了以下工作。但它只加载一个控制器。 HTML

     <a  href="#/total" > Get Total Data </a></br></br>
<div ng-view style="position: absolute; text-align: left; ">>
 </div></p>
     </div>
     <div>
   <script type="text/ng-template" id="test.html">
  <h1 class= "tile tileLargo amarelo" >Total Places: {{places.places}}</h1>

  <h1 class= "tile tileLargo azul"  >Total Users: {{users.users}}</h1>


  <h1  >Total Coolios: {{coolios.coolios}}</h1>


  </script>
   </div>

角: 路线:

myApp .config(['$routeProvider',
 function($routeProvider) {
  $routeProvider.
  when('/total', {
    templateUrl: 'test.html',
    controller: 'TotalplacesCtrl'
  }).
    when('/total', {
    templateUrl: 'test.html',
    controller: 'TotalUserCtrl'
  }).  when('/total', {
    templateUrl: 'test.html',
    controller: 'TotalCoolioCtrl'
  }).

Contollers:

   myApp.controller('TotalUserCtrl', function($scope,$http) {

   $http.get('http://94.125.132.253:8001/gettotalusers').success(function (data) {

   $scope.users = data;
   console.log(data);
    }

     )});  //Total coolios

     myApp.controller('TotalCoolioCtrl', function($scope,$http) {
     $http.get('http://94.125.132.253:8001/gettotalcoolios').success(function (data) {
   $scope.coolios = data;
  console.log(data);
  }
  )}); 
  //Total coolios
  myApp.controller('TotalplacesCtrl', function($scope,$http) {

 $http.get('http://94.125.132.253:8001/gettotalplaces').success(function (data) {
 $scope.places = data;
 console.log(data);
  }
  )}); 

我该如何解决?棱角分明,我很新。但这是我到目前为止所做的。

1 个答案:

答案 0 :(得分:0)

在这种情况下,只会触发最后一个路由处理程序,因为每个定义都会覆盖最后一个。我可以想到几个替代方案 - 使用UI Router并使用嵌套状态或直接在要使用该控制器呈现的每个元素上指定控制器...例如。

<强>的Javascript

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

app.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/total', {
        templateUrl: 'test.html',
        controller: 'TotalCtrl'
    });
}])
.controller('TotalCtrl', function($scope) {
})
.controller('TotalPlacesCtrl', function($scope) {
    $scope.places = {
        places: 24
    };
})
.controller('TotalUsersCtrl', function($scope) {
    $scope.users = {
        users: 55
    };
})
.controller('TotalCooliosCtrl', function($scope) {
    $scope.coolios = {
        coolios: 18
    };
});

**模板**

<script type="text/ng-template" id="test.html">
  <h1 ng-controller="TotalPlacesCtrl">Total Places: {{places.places}}</h1>
  <h1 ng-controller="TotalUsersCtrl">Total Users: {{users.users}}</h1>
  <h1 ng-controller="TotalCooliosCtrl">Total Coolios: {{coolios.coolios}}</h1>
</script>

另外Plunker来演示。