【发布时间】:2015-05-08 08:25:54
【问题描述】:
我有服务方法,
var selectedType = 0;
.........
.........
return {
updateType: function (type) {
return selectedType = type;
},
getType: function () {
return selectedType;
}
}
我想在 2 个控制器之间共享这个 selectedType 变量。因此,从一个控制器调用 updateType 方法并打开一个新的弹出页面,我在其中调用 getType 方法。
问题是,getType 方法在弹出页面中总是返回 0,但从主页面分配的值是 2(通过调用 updateType 方法)。
主页,
angular.module('Controller1Module', [])
.controller('myController1', ['$scope', 'myService',
function ($scope, myService) {
myService.updateType(1);
$scope.$watch(myService.getType , function(newValue, oldValue){
$scope.selectedType = myService.getType();
});
}
弹出控制器,
angular.module('Controller2Module', [])
.controller('myController', ['$scope', 'myService',
function ($scope, myService) {
$scope.$watch(myService.getType , function(newValue, oldValue){
$scope.selectedType = myService.getType();
});
}
我的服务,
angular.module('serviceModule', [])
.service('myService', ['$rootScope',
function($rootScope){
var selectedType = 0;
return {
updateType: function (type) {
return selectedType = type;
},
getType: function () {
return selectedType;
}
]);
【问题讨论】:
-
你确定在getType之前调用了updateType吗?
-
您的代码应该可以工作。我这样用过很多次。请将 `var selectedType = 0;` 替换为 `var selectedType;'。请将您的代码放入小提琴并发布请`
-
如果我的控制器在不同的模块中会不会有问题?
-
@VeeraBhadra 我已经更新了我的代码,你能检查一下并提供你的输入吗?
-
@Nic 是的,Nic。请使用模块。如果你想使用不同的模块注入和使用。
标签: angularjs