WelcomeTo
WelcomeTo

Reputation: 20591

Pass object to controller in AngularJS

I have a page where I display a list of products. When the user clicks on a product I show the product details in another page. This is a part of my routing configuration:

  when('/products', {
        templateUrl: 'views/products.html',
        controller: 'ProductListCtrl'
  }).
  when('/products'/:productId', {
         templateUrl: 'views/product-details.html',
         controller: 'ProductDetailsCtrl'
  }).

As you can see I can only pass productId (which I retrieve using $routeParams) as parameter, which means I need to make another AJAX call to get information about product. But I already have this data on the products page.

So my question is: can I pass a whole Product object to ProductDetailsCtrl instead of just passing productId?

Upvotes: 2

Views: 174

Answers (3)

cbass
cbass

Reputation: 2558

To actually pass an object into the controller you should use the resolve property. In the end you will have to use your service to retrieve the object. But you will get a more loosely coupled solution by not having to pass the object the service and then back to a controller. Consider the following example:

 $routeProvider
   .when('/product/:productId', {
   templateUrl: 'product-details.html',
   controller: 'ProductDetailsController',
   resolve: {
      product: productService.getProductById($routeParams.productId);
   }
 });

 productApp.controller("ProductDetailsController", function($scope, product) {
   $scope.product = product;
 });

You can read more about it at the angular docs.

Upvotes: 0

Liad Livnat
Liad Livnat

Reputation: 7475

yes you can use shared properties service and pass elements between controllers:

.service('sharedProperties', function () {
    var item = null;
    return {
        getItem: function () {
            return item;
        },
        setItem: function(value) {
            item = value;
        }
    }});

Then before you move to controller you use:

sharedProperties.setItem(your-item);

and after you load the new controller you use:

var model = sharedProperties.getItem();

Upvotes: 0

Andy Gaskell
Andy Gaskell

Reputation: 31761

You can use a Product service. In the ProductListCtrl the service would make the http calls and cache the results. The ProductDetailsCtrl would also use Product service. Your service can then return a product from the cache instead of making another http request.

Upvotes: 1

Related Questions