Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have a basic controller that displays my products,

App.controller('ProductCtrl',function($scope,$productFactory){ 

$productFactory.get().success(function(data){ 

$scope.products = data; 

}); 

});

In my view I'm displaying this products in a list

<ul> 

<li ng-repeat="product as products"> 

{{product.name}} 

</li> 

</ul

What I'm trying to do is when someone clicks on the product name, I have another view named cart where this product is added.

<ul class="cart"> 

<li> //click one added here </li> 

<li> //click two added here </li> 

</ul>

So my question here is, how do pass this clicked products from the first controller to the second? I assumed that cart should be a controller too.

I handle click event using directive. Also, I feel I should be using service to achieve above functionality just can't figure how? because cart will be a predefined number of products added could be 5/10 depending on which page the user is. So I would like to keep this generic.

1 Answer

0 votes
by (106k points)

For passing data between controllers in AngularJS you can define your product service as follows:-

app.factory('productService', function() { 

var productList = []; 

var addProduct = function(newObj) { 

productList.push(newObj); 

}; 

var getProducts = function(){ 

return productList; 

}; 

return { 

addProduct: addProduct, 

getProducts: getProducts 

}; 

});

Related questions

0 votes
1 answer
+2 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...