我正在尝试在 Controller 和函数之间共享变量。但我从 Controller 收到一个错误,说:
TypeError: Cannot read property 'getSet' of undefined
我已经阅读了很多教程,但不知道我哪里出错了。 我的服务代码是这样的:
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
:
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);
};
};
我的 Controller 是这样的:
app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, $mdToast, shareData) {
console.log(shareData.getSet()); // NOT WORKING
}]);
最佳答案
您的 topicController
Controller 的工厂函数中有额外的 $mdToast
,您需要将其删除。
它不起作用的原因是,目前您在数组中提到了 4 个依赖项,例如 ['$scope', '$http', '$mdDialog', 'shareData', function
&那么您将在 DI 数组旁边的函数内使用它的实例。在该函数内部,实际上有 5 个依赖项,其中 $mdToast
是额外的。因此,在幕后发生的事情是函数的 $scope
持有 '$scope'
DI 数组的值,同样,您从右到左。但是,当涉及到 $mdToast
(在 Controller 函数中)时,它保存了 'shareData'
(DI 数组)的值,然后是下一个参数 shareData
什么也没得到。
app.controller('topicController', ['$scope', '$http', '$mdDialog', 'shareData',
function ($scope, $http, $mdDialog, shareData) { //<--removed $mdToast
console.log(shareData.getSet());
}
]);
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.
关于javascript - Angular : Not able to access variables in controller using service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968742/