0

Like many before I want to pass data between controllers. Specifically I want the user to be able to keep track of creating another user. I looked at the following SO explanations and came away not getting the results I was looking for or with answers that I don't know how to implement:

How can I pass some data from one controller to another peer controller

angularjs - passing data between controllers

AngularJS: How can I pass variables between controllers?

I also don't think broadcast is the solution to the problem. I think this is something that should be done with a service or factory (either will do as long as it works since I don't really understand the difference between them right now)

My code:

SERVICE

angular.module('startupApp')
  .service('vendorId', function () {
    // AngularJS will instantiate a singleton by calling "new" on this function
      var VendorId = [];
      var Vendor = [];

      return {
        setVendorId: function(vendorId){
          VendorId.push(vendorId);
        },
        getVendorId: function(){
          return VendorId;
        },
        setVendor: function(vendor){
          Vendor.push(vendor);
        },
        getVendor: function(){
          return Vendor;
        }

      };
  });

CONTROLLER 1

angular.module('startupApp')
    .controller('controller1', function ($scope, Auth, $location, vendorId, $http) {

         $scope.user = {};
         vendorId.setVendor($scope.user);
         vendorId.setVendorId($scope.user.id);
})

CONTROLLER 2

angular.module('startupApp')
        .controller('controller2', function ($scope, Auth, $location, vendorId, $http) {

         console.log(vendorId.getVendor());//[]     
         console.log(vendorId.getVendorId());//[]

})

These both end up as empty arrays. To be clear, there is page1.html that has a form that populates the $scope.user object in controller1. I want to be able to get this object on page2.html from the page2.html controller (controller2)

Community
  • 1
  • 1
rashadb
  • 2,515
  • 4
  • 32
  • 57
  • So what's unclear or what's wrong with this question? I'm sure it's simple but I'm not getting it. – rashadb Oct 09 '15 at 23:39
  • 1
    The service is a singleton, so the way you implemented is correct. The reason you're getting `[]` is probably because `controller2` runs before `controller1` had a chance to run and call `.setVendor` – New Dev Oct 09 '15 at 23:45
  • 1
    As a side note: both `.factory` and `.service` create a singleton ***service***. The difference is in the method of creation. `.factory` expects a function that returns the created service instance (thus, it's a factory function). `.service` expects a constructor function and calls `new` on it to get the service instance. – New Dev Oct 09 '15 at 23:47
  • @New Dev, thanks for the feedback. How do I prevent controller 2 from running before controller 1? I use Angular Fullstack and it's a single page app. – rashadb Oct 09 '15 at 23:49
  • Controllers run in the order that they appear in the DOM. But you shouldn't even be in this situation (i.e. that you need to "prevent"). Controllers are meant to setup the ViewModel. There is no reason to have the controller automatically add data to the service - you might as well have the service add the data when it's created. – New Dev Oct 09 '15 at 23:52
  • @New Dev, I'm not clear what you mean. User 1 is logged in on page1/controller1. Page 1 is for creating new users. Once a new user is created I want to save the identity of that user with the service before going to page 2. Page 2 I look up the newly created user using vendorId.getVendor() so that I can add information to the new user. Where am I going wrong? – rashadb Oct 10 '15 at 00:03

1 Answers1

1

Your code should work, unless controller1 is not invoked before controller2.

run this code snippet and see by yourself.

angular.module("test", [])
    .service("vendorId", function () {
      var VendorId = [];
      var Vendor = [];

      return {
        setVendorId: function(vendorId){
          VendorId.push(vendorId);
        },
        getVendorId: function(){
          return VendorId;
        },
        setVendor: function(vendor){
          Vendor.push(vendor);
        },
        getVendor: function(){
          return Vendor;
        }

      };
    })
      .controller("Controller1", function ($rootScope, vendorId) {
        
        this.user = {id : 1};
        this.save = function () {
           vendorId.setVendor(this.user);
           vendorId.setVendorId(this.user.id);
  
            // simulates page change
            $rootScope.saved = true;
          }
      })
      .controller("Controller2", function (vendorId) {
          this.user  = vendorId.getVendor();
          this.id = vendorId.getVendorId();
      })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div data-ng-app="test">
      <div data-ng-if="!saved" data-ng-controller="Controller1 as scope1">
        <input type="text" data-ng-model="scope1.user.name" />
        <button data-ng-click="scope1.save()">Save</button>
      </div>
      
      <div data-ng-if="saved" data-ng-controller="Controller2 as scope2">
        The user : {{scope2.user}} <br />
        The user id : {{scope2.id}}
      </div>
    </div>
  • Thanks. I tried your code and it makes sense and it works. But I'm not getting anything but a blank array when I go from one page to the next. Starting with page1/controller1 where I set the user using the service. When I got to page2/controller2 and try to get the user there is only a blank array. – rashadb Oct 09 '15 at 23:57
  • 1
    I need to see your code in order to help you, because, basically, it should work, but you can be adding somewhere a line of code that empty the array, I don't know. – أنيس بوهاشم Oct 10 '15 at 00:02
  • Could it be the var VendorId = []; clears the service of data as you switch between controllers since they're on different pages and instantiated in different controllers? – rashadb Oct 10 '15 at 00:05
  • no that's not possible, the service is instantiated only once, so that can't happen. – أنيس بوهاشم Oct 10 '15 at 00:07
  • The problem was that multiple browser windows were open I think – rashadb Oct 10 '15 at 00:10
  • simple, try with just one browser, and you will see, this is not the problem unless you're using a sort of data synchronisation, but you didn't show that in your code. – أنيس بوهاشم Oct 10 '15 at 00:12
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/91892/discussion-between---and-rashadb). – أنيس بوهاشم Oct 10 '15 at 00:14
  • 1
    No I figured it out! Thanks bunch for helping. I plussed you. All the best man! – rashadb Oct 10 '15 at 00:15