0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you. But can I also inject a little bit more variables? For example I also want variable needToShowFilter, and if its products then this variable should be true othervise false
You can create additional resolve property in the routes as i have created above and then you can inject the same into the controller
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.