[英]Sharing data between controllers in Angular JS?
在將此標記為重復之前,我已經閱讀了很多類似的問題,但是我發現的所有答案似乎都使用$ scope,並且在閱讀了文檔之后,我不確定自己是否理解$ scope,或者為什么我知道d在這種情況下使用它。
我發現本教程描述了如何做我想做的事情。
但是,它使用的是數據數組。 我只需要一個實數變量。 另外,我不知道他為什么要為他創建的工廠服務聲明一個附加對象; 為什么不僅僅使用工廠作為對象?
我當時以為可以做這樣的事情,但是我不確定它是否會起作用。
創建我的工廠/服務:
var demoModule = angular.module("demoModule", []);
demoModule.factory("demoService", function() {
var demoSharedVariable = null;
return demoSharedVariable;
});
訪問每個控制器中的共享變量:
var demoControllerOne = demoModule.controller("demoContollerOne", function(demoSharedVariable) {
this.oneFunction = function(oneInput){
demoSharedVariable = oneInput;
};
});
var demoControllerTwo = demoModule.controller("demoContollerTwo", function(demoSharedVariable) {
this.twoFunction = function(twoInput){
demoSharedVariable = twoInput;
};
});
這種方法會產生我想要的共享變量嗎?
您需要注入服務才能使用它,然后訪問服務變量。
demoModule.controller("demoContollerOne", function($scope, demoService) {
$scope.oneFunction = function(){
demoService.demoSharedVariable = $scope.oneInput;
};
});
demoModule.controller("demoContollerTwo", function($scope, demoService) {
$scope.twoFunction = function(){
demoService.demoSharedVariable = $scope.twoInput;
};
});
如果使用controllerAs,則很少(或不應)注入並使用$ scope。 由於controllerAs是一個相對較新的功能,所以那時我們別無選擇,只能使用$ scope,因此使用$ scope查找示例並不奇怪。
編輯:如果您不使用controllerAs(如本例中所示),則需要$ scope將函數或變量公開給視圖。
擺弄它時,有幾個地方不正確,我將編輯代碼。 我不知道如何在不使用$ watch等高級概念的情況下展示效果,如果您不了解,請提供您自己的小提琴。
重要的一件事是,如果您想使用角度,則必須了解范圍的知識。
由於您的工廠或控制器都不正確,因此我為您編寫了一個簡單的示例來幫助您了解服務:
服務:
angular.module('myApp').service('MyService', [function() {
var yourSharedVariable; // Your shared variable
//Provide the setter and getter methods
this.setSharedVariable = function (newVal) {
yourSharedVariable = newVal;
};
this.getSharedVariable = function () {
return yourSharedVariable;
};
}
]);
控制器:
myApp.controller('Ctrl2', ['$scope', 'MyService', '$window', function($scope, MyService, $window) {//inject MyService into the controller
$scope.setShared = function(val) {
MyService.setSharedVariable(val);
};
$scope.getShared = function() {
return MyService.getSharedVariable();
};
$scope.alertSharedVariable = function () {
$window.alert(MyService.getSharedVariable());
};
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.