Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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.

share|improve this question

1 Answer 1

up vote 0 down vote accepted
<div ng-controller="universalController" ng-init="initialize('books')>

or

<div ng-repeat="category in allCategories">
    <div ng-controller="universalController">
        <!-- the controller's $scope.category contains the category 
             of the controller -->
share|improve this answer
    
This will work when I will have div blocks of each category placed "side-by-side". What if they all are in different place of the DOM? – kaytrance Aug 26 '14 at 6:49
    
Then use the first snippet. – JB Nizet Aug 26 '14 at 6:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.