WelcomeTo
WelcomeTo

Reputation: 20581

AngularJS. Initialize controller with different data

I'm using $routeProvider for routing in my Angular app. And for 2 routes I'm using same HTML template and same Controller.

        when('/products, {
            templateUrl: 'views/products.html',
            controller: 'ProductListCtrl'
        }).
        when('/myProducts', {
            templateUrl: 'views/products.html',
            controller: 'ProductListCtrl'
        }).

Only difference in data that I want to show. I.e. for path products I want AJAX request to myserver:8080/products and for for path myProducts I want to load data from AJAX request to myserver:8080/products/my.

For now I i'm using $location service to distinguish the current page (products or myProducts) and load apropriate data.

Is there some more elegant way to do it? For example using resolve method of $routeProvider?

Upvotes: 0

Views: 68

Answers (2)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

The best way to reuse controller name in today scenario is to use resolve with $routeparams.

You can modify your code as below

 when('/products, {
                templateUrl: 'views/products.html',
                controller: 'ProductListCtrl',
    resolve: {
            product: function($http) {
              return $http.get('/products')
            },
              needToShowFilter:function($q){
               var showfilter = $q.defer();
                   showfilter.resolve(false);
               return showfilter.promise
            }
          }
            }).
            when('/myProducts', {
                templateUrl: 'views/products.html',
                controller: 'ProductListCtrl',
    resolve: {
            product: function($http) {
              return $http.get('/products/my')
            },
            needToShowFilter:function($q){
               var showfilter = $q.defer();
                   showfilter.resolve(true);
               return showfilter.promise
            }
          }
            }).

And then in your controller you can inject the product into the controller code.

Upvotes: 2

t0mpl
t0mpl

Reputation: 5025

try to add $route in your controller, and log

$route.current

to see what you have inside, i think thats the way to get the information

Upvotes: 0

Related Questions