...">

Use the same controller twice with different data

I have the following setup:

<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>

I cannot understand how to reuse the html table and controller, but pass a different value for the type, so the Items service returns different results for the two tables.

I know that I can create two controllers and inherit from BaseItemsController, but this does not look right for me. Any better ideas?

Thanks!

+4
source share
2 answers

Here is my solution:

<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>
+2
source

Based on your sample scenario, I advise you to use one controller and filter the item type: Current | The past in your repeater. Like this:

<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>

This is one set of items.

,

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

1:

, $routeparams .

+3

Source: https://habr.com/ru/post/1524537/


All Articles