Pass an object between controllers

2

I am trying to have two controllers share an object, that is, from a view I want to send an object to another view, but I can not get it in the view that receives this object. For this I created a service:

angular.module("panelYerrandApp").service('ItemComercioSV', function () { 
// this.comercio = item
this.itemcomercio = [];

this.setItemComercio = function (item) {
    this.itemcomercio = item;
}

this.getItemComercio = function () {
    return this.itemcomercio;
}
});

In both controllers I inject the service, from one view I assign the item and from the other I recover it but I get 'undefined'. Can this be done?

    
asked by Iban Lopez 22.07.2016 в 13:18
source

2 answers

1

Starting from the base of this answer :

To send variables between multiple controllers, a service is used to inject in any controller:

Sample service:

angular.module('myApp', [])
    .service('sharedProperties', function () {
        var property = 'First';

        return {
            getProperty: function () {
                return property;
            },
            setProperty: function(value) {
                property = value;
            }
        };
    });

Usage:

function Ctrl2($scope, sharedProperties) {
    $scope.prop2 = "Second";
    $scope.both = sharedProperties.getProperty() + $scope.prop2;
}

And a fiddle that uses it.

    
answered by 22.07.2016 в 14:40
0

What you question, depends on the context.

In the case of working with status (ui.router), it is easier to pass parameters through the state, if the two controllers are in the same view and require a common variable, what I recommend is the use of providers. although the service will work, but it is not the best practice.

I recommend you read more about good practices in Mr. John Papa's angle in the following link: link

    
answered by 22.07.2016 в 17:15