2014-01-30 39 views
4

我有以下设置:不同的数据使用相同的控制器两次

<h2>Current Items</h2> 
<table ng-controller="ItemsController"> 
    <tr ng-repeat="item in items"> 
     <td>{{item.id}}</td> 
    </tr> 
</table> 

<h2>Past Items</h2> 
<table ng-controller="ItemsController"> 
    <tr ng-repeat="item in items"> 
     <td>{{item.id}}</td> 
    </tr> 
</table> 

<script> 
    var app = angular.module('app'); 

    app.factory('Items', ['$resource', function ($resource) { 
     return $resource('/api/items/:id/', {id: '@id'}); 
    }]); 

    app.controller("ItemsController", function($scope, Items) { 
     $scope.items = Items.query({type: 'current'}); 
    }); 
</script> 

我不明白如何再利用HTML表格和控制器,而是通过对类型不同的值,所以该项目服务返回两个表的不同结果。

我知道我可以创建两个控制器并从一个BaseItemsController继承,但它看起来不正确。任何更好的想法?

谢谢!

回答

2

这里是我的解决方案:根据您的示例场景

<h2>Current Items</h2> 
<div ng-controller="ItemsController"> 
    <div ng-include="'items.html'" onload="init('current')"></div> 
</div> 

<h2>Past Items</h2> 
<div ng-controller="ItemsController"> 
    <div ng-include="'items.html'" onload="init('past')"></div> 
</div> 

<script type="text/ng-template" id="items.html"> 
    <table ng-controller="ItemsController"> 
     <tr ng-repeat="item in items"> 
      <td>{{item.id}}</td> 
     </tr> 
    </table> 
</script> 

<script> 
    var app = angular.module('app'); 

    app.factory('Items', ['$resource', function ($resource) { 
     return $resource('/api/items/:id/', {id: '@id'}); 
    }]); 

    app.controller("ItemsController", function($scope, Items) { 
     $scope.items = []; 

     $scope.init = function (type) { 
      $scope.items = Items.query({type: type}); 
     };   
    }); 
</script> 
3

我的建议是,你需要使用一个控制器和筛选项目类型:当前|过去在你的中继器。像这样:

<div ng-controller="ItemsController"> 
<h2>Current Items</h2> 
<table > 
    <tr ng-repeat="item in items | filter: /*CURRENT items*/"> 
     <td>{{item.id}}</td> 
    </tr> 
</table> 

<h2>Past Items</h2> 
<table > 
    <tr ng-repeat="item in items | filter: /*PAST items*/"> 
     <td>{{item.id}}</td> 
    </tr> 
</table> 
</div> 

这是与一组项目。

或者,您可以有两个项目集合在你的控制器一样

$scope.pastItems = []; 
$scope.currentItems=[]; 

更新1:

如果您在不同的页面上使用您的控制器,你可以设置一个路由,并与$routeparams通在不同的初始化上。

相关问题