Imagine we have a product list with 3 categories: books, fruits and electronics. Next we want to get 10 products from each category and display them. And for future we need to bear in mind that we want our category scope to be independent, so we could apply some manipulations with the gathered data later.
What we need is some kind of universal controller with parameter equal to category name so that we could fetch this param to factory to get data from server, and then output it.
Idealy it seems to me that we need to code it that way:
<div ng-controller="universalController('books')">
<ul>
<li ng-repeat="product in products">{{ product }}</li>
</ul>
</div>
<div ng-controller="universalController('fruits')">
<ul>
<li ng-repeat="product in products">{{ product }}</li>
</ul>
</div>
<div ng-controller="universalController('electronics')">
<ul>
<li ng-repeat="product in products">{{ product }}</li>
</ul>
</div>
And our controller must be something like this:
var app = angular.module( 'mainApp', ['ngResource'] );
app
.factory( 'Products', [ '$resource', function( $resource ) {
return $resource( '/api/:category', {}, {'get': { method: "GET" , isArray:true } } );
}])
.controller( 'universalController', [ '$scope', 'Products', 'Category', function( $scope, Products, Category ) {
setTimeout(function() {
$scope.products = Products.get({category: Category});
}, 3000);
}]);
This will not work, of course, but how to implement this functionality in angular? Clearly that making 3 separate controllers with different name would be kind of a lame solution, so I am wondering is there a way to create something like I described.