Antonis Kountouretis February 2016

pass more than one variable in angularjs?

app.factory('dataPassingService', function() {
var savedData = {};
function set(data) {
    savedData = data;
}
function get() {
    return savedData;
}

return {
    set: set,
    get: get
}
});

controller1

$scope.text = '9';
     dataPassingService.set($scope.text);

controller2

 $scope.mes = dataPassingService.get();
 alert("the scope is "+scope.mes);

I pass the $scope.text from controller1 to controller 2 using app.factory and it work perfect. i would like to pass more scopes together from controller1 to controller2 for example i would like to pass $scope.text='9' and scope.text1='10' and then with the take it to the controller2 with datapassingService.get().Thanks in advance

Answers


Seaal February 2016

You could pass in a key to uniquely identify each different piece of data, for example:

app.factory('dataPassingService', function() {
    var savedData = {};

    function set(key, data) {
        savedData[key] = data;
    }

    function get(key) {
        return savedData[key];
    }

    return {
        set: set,
        get: get
    }
});

Usage:

Controller 1

$scope.text = '9';
dataPassingService.set("myKey", $scope.text);
dataPassingService.set("message", "foo");

Controller 2

$scope.mes = dataPassingService.get("myKey");
$scope.message = dataPassingService.get("message");
alert("the scope is " + $scope.mes); // the scope is 9

Post Status

Asked in February 2016
Viewed 2,260 times
Voted 7
Answered 1 times

Search




Leave an answer