2016-02-08 68 views
0
app.factory('dataPassingService', function() { 
var savedData = {}; 
function set(data) { 
    savedData = data; 
} 
function get() { 
    return savedData; 
} 

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

控制器1在angularjs中傳遞多個變量?

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

控制器2

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

我通過$ scope.text從控制器1使用app.factory 2和它的工作完美控制器。我想將更多的範圍從controller1傳遞給controller2例如我想通過$ scope.text ='9'和scope.text1 = '10',然後通過datapassingService.get()將其傳遞給controller2。預先.Thanks

回答

2

你可以通過在密鑰唯一地識別每個不同的數據段,例如:

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

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

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

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

用法:

控制器1

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

控制器2