Passing data between controllers in Angular JS? Passing data between controllers in Angular JS? angularjs angularjs

Passing data between controllers in Angular JS?


From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples.

You could define your product service (as a factory) as such:

app.factory('productService', function() {  var productList = [];  var addProduct = function(newObj) {      productList.push(newObj);  };  var getProducts = function(){      return productList;  };  return {    addProduct: addProduct,    getProducts: getProducts  };});

Dependency inject the service into both controllers.

In your ProductController, define some action that adds the selected object to the array:

app.controller('ProductController', function($scope, productService) {    $scope.callToAddToProductList = function(currObj){        productService.addProduct(currObj);    };});

In your CartController, get the products from the service:

app.controller('CartController', function($scope, productService) {    $scope.products = productService.getProducts();});


how do pass this clicked products from first controller to second?

On click you can call method that invokes broadcast:

$rootScope.$broadcast('SOME_TAG', 'your value');

and the second controller will listen on this tag like:

$scope.$on('SOME_TAG', function(response) {      // ....})

Since we can't inject $scope into services, there is nothing like a singleton $scope.

But we can inject $rootScope. So if you store value into the Service, you can run $rootScope.$broadcast('SOME_TAG', 'your value'); in the Service body. (See @Charx description about services)

app.service('productService',  function($rootScope) {/*....*/}

Please check good article about $broadcast, $emit


Solution without creating Service, using $rootScope:

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.

var app = angular.module('mymodule',[]);app.controller('Ctrl1', ['$scope','$rootScope',  function($scope, $rootScope) {    $rootScope.showBanner = true;}]);app.controller('Ctrl2', ['$scope','$rootScope',  function($scope, $rootScope) {    $rootScope.showBanner = false;}]);

Using $rootScope in a template (Access properties with $root):

<div ng-controller="Ctrl1">    <div class="banner" ng-show="$root.showBanner"> </div></div>