Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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 click 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 doubt here is, how do pass this clicked products from first controller to 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 predefined number of products added could be 5/10 depending on which page user is. So i would like to keep this generic.

Update:

I created a service to broadcast and in the second controller i receive it. Now the query is how do i update dom? Since my list to drop product is pretty hardcoded.

share|improve this question
    
Possible duplicate of Pass variables to AngularJS controller, best practice? – T.Todua Sep 20 '16 at 11:29

15 Answers 15

up vote 269 down vote accepted

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 such:

app.service('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();
});
share|improve this answer
3  
Cart controller will update once when getProducts() is called? Or every time new product is added? – kishanio Nov 24 '13 at 22:02
1  
If you want it to automatically update, you can add the broadcast from Maxim Shoustin's answer and call getProducts() within the $on function to update the CartCtrl's scope. – Charx Nov 24 '13 at 22:21
2  
@krillgar You are completely correct, that was overlooked initially. I've edited the answer to reflect a working solution. – Charx Jun 6 '14 at 19:27
1  
@DeveshM Yes, do as you suggest. You may want to consider extending the methods so they are not just holding data in memory and to be more persistent (save to server via $http call, for example). – Charx Aug 24 '15 at 0:26
1  
What happens if I have 2 productControllers and 2 carts for example? Both will have the element added? How do you solve that in this case? – atoth Feb 25 '16 at 15:28

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

share|improve this answer
1  
Yup this works like charm I'm using factory? There is just one last thing where I'm stuck i do get data in new controller every time i click product. Now how do i update it in DOM? Because i already have lets say list of 5 hardcoded with borders so each products need to go inside them – kishanio Nov 24 '13 at 22:47
1  
@KT - Did you ever get an answer? It seems like an obvious question but I can't find the answer anywhere. I want a controller to change some value. When that app value changes then any other listening controllers should update themselves as necessary. Can't find it. – daylight Feb 28 '14 at 18:52
2  
@daylight the answer on your q. is based on what controller structure you have: parallel or child-parent. $rootScope.$broadcast notifies all controllers that have parallel structure aka the same level. – Maxim Shoustin Feb 28 '14 at 19:33
    
@MS Thanks for the reply. Is there a way to do this using $watch? BTW, Mine are parallel controllers and I got it to work using your method. For me, whenever I try to add the $watch (even to $rootScope) the method associated with the $watch in the 2nd controller would only fire the first time (initialization of the 2nd controller). Thanks. – daylight Feb 28 '14 at 20:34
1  
we can use $watch if the value exists on $rootScope level. Otherwise only broadcast might notify other controllers. FYI, if other programmer sees in your code broadcast - the logic is clear what you try to do - "broadcast event". Anyways, from my exp. its not good practice to use rootscope for watch. About "fire 1st time only": take a look on this example: plnkr.co/edit/5zqkj7iYloeHYkzK1Prt?p=preview you have old and new values. be sure that each time you get new value that doesnt equal to old one – Maxim Shoustin Feb 28 '14 at 22:32

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>
share|improve this answer
18  
$rootScope should be avoided as much as possible. – Shaz Sep 10 '14 at 15:09
1  
@Shaz could you elaborate why? – Mirko Sep 11 '14 at 14:17
3  
@Mirko You should try to avoid global state as much as you can because anyone can change it -making your program state unpredictable. – Umut Seven Sep 12 '14 at 12:36
4  
$rootScope has global scope, so like native global variables we have to use them carefully. If any controller changes its values, it will get changed for global scope. – Sanjeev Dec 7 '14 at 6:59
1  
Services are singleton, and also have global scope....so, uh...same issue. – Mark Brackett May 21 '15 at 14:47

You can do this by two methods.

  1. By using $rootscope, but I don't reccommend this. The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable.

  2. Using services. You can do this by sharing a service between two controllers. Code for service may look like this:

    app.service('shareDataService', function() {
        var myList = [];
    
        var addList = function(newObj) {
            myList.push(newObj);
        }
    
        var getList = function(){
            return myList;
        }
    
        return {
            addList: addList,
            getList: getList
        };
    });
    

    You can see my fiddle here.

share|improve this answer

An even simpler way to share the data between controllers is using nested data structures. Instead of, for example

$scope.customer = {};

we can use

$scope.data = { customer: {} };

The data property will be inherited from parent scope so we can overwrite its fields, keeping the access from other controllers.

share|improve this answer
1  
Controllers inherit scope properties from parent Controllers to its own scope. Clean! simplicity makes it beatiful – Carlos R Balebona Apr 1 '15 at 5:18
    
cant make it work. on the second controller I use $scope.data and it's undefined. – Bart Calixto Jul 30 '15 at 16:26
angular.module('testAppControllers', [])
    .controller('ctrlOne', function ($scope) {
        $scope.$broadcast('test');
    })
    .controller('ctrlTwo', function ($scope) {
        $scope.$on('test', function() {
        });
    });
share|improve this answer
    
this piece of code is for ngroute Or ui.route ? – vijay Jan 20 at 6:48

I've created a factory that controls shared scope between route path's pattern, so you can maintain the shared data just when users are navigating in the same route parent path.

.controller('CadastroController', ['$scope', 'RouteSharedScope',
    function($scope, routeSharedScope) {
      var customerScope = routeSharedScope.scopeFor('/Customer');
      //var indexScope = routeSharedScope.scopeFor('/');
    }
 ])

So, if the user goes to another route path, for example '/Support', the shared data for path '/Customer' will be automatically destroyed. But, if instead of this the user goes to 'child' paths, like '/Customer/1' or '/Customer/list' the the scope won't be destroyed.

You can see an sample here: http://plnkr.co/edit/OL8of9

share|improve this answer

I saw the answers here, and it is answering the question of sharing data between controllers, but what should I do if I want one controller to notify the other about the fact that the data has been changed (without using broadcast)? EASY! Just using the famous visitor pattern:

myApp.service('myService', function() {

    var visitors = [];

    var registerVisitor = function (visitor) {
        visitors.push(visitor);
    }

    var notifyAll = function() {
        for (var index = 0; index < visitors.length; ++index)
            visitors[index].visit();
    }

    var myData = ["some", "list", "of", "data"];

    var setData = function (newData) {
        myData = newData;
        notifyAll();
    }

    var getData = function () {
        return myData;
    }

    return {
        registerVisitor: registerVisitor,
        setData: setData,
        getData: getData
    };
}

myApp.controller('firstController', ['$scope', 'myService',
    function firstController($scope, myService) {

        var setData = function (data) {
            myService.setData(data);
        }

    }
]);

myApp.controller('secondController', ['$scope', 'myService',
    function secondController($scope, myService) {

        myService.registerVisitor(this);

        this.visit = function () {
            $scope.data = myService.getData();
        }

        $scope.data = myService.getData();
    }
]);

In this simple manner, one controller can update another controller that some data has been updated.

share|improve this answer
2  
Wouldn't the observer pattern (en.wikipedia.org/wiki/Observer_pattern) be more relevant here? Visitor pattern is something else... en.wikipedia.org/wiki/Visitor_pattern – Ant Kutschera Apr 7 '15 at 19:10

Make a factory in your module and add a reference of the factory in controller and use its variables in the controller and now get the value of data in another controller by adding reference where ever you want

share|improve this answer

I don't know if it will help anyone, but based on Charx (thanks!) answer I have created simple cache service. Feel free to use, remix and share:

angular.service('cache', function() {
    var _cache, _store, _get, _set, _clear;
    _cache = {};

    _store = function(data) {
        angular.merge(_cache, data);
    };

    _set = function(data) {
        _cache = angular.extend({}, data);
    };

    _get = function(key) {
        if(key == null) {
            return _cache;
        } else {
            return _cache[key];
        }
    };

    _clear = function() {
        _cache = {};
    };

    return {
        get: _get,
        set: _set,
        store: _store,
        clear: _clear
    };
});
share|improve this answer

FYI The $scope Object has the $emit, $broadcast, $on AND The $rootScope Object has the identical $emit, $broadcast, $on

read more about publish/subscribe design pattern in angular here

share|improve this answer

There are three ways to do it,

a) using a service

b) Exploiting depending parent/child relation between controller scopes.

c) In Angular 2.0 "As" keyword will be pass the data from one controller to another.

For more information with example, Please check the below link :

http://www.learnit.net.in/2016/03/angular-js.html

share|improve this answer

we can store data in session and can use it anywhere in out program.

$window.sessionStorage.setItem("Mydata",data);

Other place

$scope.data = $window.sessionStorage.getItem("Mydata");
share|improve this answer

One way using angular service:

var app = angular.module("home", []);

app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});


app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});

app.factory('ser1', function(){
return {o: ''};
});



<div ng-app='home'>

<div ng-controller='one'>
  Type in text: 
  <input type='text' ng-model="inputText.o"/>
</div>
<br />

<div ng-controller='two'>
  Type in text:
  <input type='text' ng-model="inputTextTwo.o"/>
</div>

</div>

https://jsfiddle.net/1w64222q/

share|improve this answer

To improve the solution proposed by @Maxim using $broadcast, send data don't change

$rootScope.$broadcast('SOME_TAG', 'my variable');

but to listening data

$scope.$on('SOME_TAG', function(event, args) {
    console.log("My variable is", args);// args is value of your variable
})
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.