Angular:无法使用服务访问控制器中的变量 [英] Angular: Not able to access variables in controller using service
问题描述
我正在尝试在控制器和功能之间共享变量.但是我从控制器收到一个错误,说:
I am trying to share a variable between a controller and a function. But i get an error from the controller, saying this:
TypeError: Cannot read property 'getSet' of undefined
我已经看过很多教程,但是不知道我要去哪里. 我的服务代码如下:
I have gone through numerous tutorials, but don't know where am I going wrong. My service code is like this:
app.service('shareData', function() {
var selected = ["plz", "print", "something"];
var putSet = function(set) {
selected = set;
};
var getSet = function() {
return selected;
};
return {
putSet: putSet,
getSet: getSet
};
});
我可以从这样定义的函数中访问selected
:
I am able to reach selected
from my function defined like this:
setDisplay = function($scope, $mdDialog, shareData) {
console.log(shareData.getSet()); // this is working
$scope.selected = shareData.getSet();
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.answer = function(answer) {
$mdDialog.hide(answer);
};
};
我的控制器是这样的:
app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, $mdToast, shareData) {
console.log(shareData.getSet()); // NOT WORKING
}]);
推荐答案
您在topicController
控制器的工厂功能中有多余的$mdToast
,您需要将其删除.
You had extra $mdToast
in your topicController
controller's factory function, you need to remove it.
它不起作用的原因是,当前您在数组中提到了4个依赖项,例如['$scope', '$http', '$mdDialog', 'shareData', function
&那么您将在DI数组旁边的函数中使用它的实例.在该函数内部,实际上有5个依赖项,其中$mdToast
个额外.因此,在幕后发生的事情是,函数$scope
持有一个'$scope'
DI数组的值,就像您从右到左走一样.但是,当涉及到$mdToast
(在控制器功能中)时,它保持的值是'shareData'
(DI数组的),并且那么下一个参数shareData
什么也不会得到.
The reason behind it was not working is, currently you had 4 dependency mentioned in array like ['$scope', '$http', '$mdDialog', 'shareData', function
& then you are using its instance inside the function next to DI array. Inside that function you had actually 5 dependencies where $mdToast
extra. So behind the scene what happening is $scope
of function hold an value of '$scope'
DI array likewise you go right to left. But when it comes to $mdToast
(in controller function) it was holding a value of 'shareData'
(of DI array) & then the next parameter shareData
get nothing.
app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, shareData) { //<--removed $mdToast
console.log(shareData.getSet());
}
]);
注意::您正在使用 DI内联数组注释,因此在数组中注入依赖项的顺序,应该以相同的顺序 然后注入基础工厂功能.
NOTE: You are using DI inline array annotation, so the sequence in which dependency are injected in array, in same sequence you should inject then in underlying factory function.
这篇关于Angular:无法使用服务访问控制器中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!