我试图从此服务获取变量,但我无法做到这一点。我已经看网上了,什么也没有。
.factory('localStorageService', function($rootScope){
$rootScope.go = function(task) {
var dataReceiver = localStorage.getItem('taskData');
var array = [];
var newArray = array.push({"title" : task});
if(dataReceiver === null) {
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
console.log(dataReceiver);
}
else {
array = JSON.parse(dataReceiver);
var newArray2 = array.push({"title" : task});
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
for(var i = 0; i < newArray2; i++) {
console.log(dataReceiver[i].title);
}
}
return dataReceiver;
}
})
控制器:
.controller('PlaylistsCtrl', function($scope, PlaylistService, localStorageService) {
console.log(localStorageService.go());
})
它说它无法读取未定义的属性go
最佳答案
您需要使用工厂所属的模块声明,这就是为什么在控制器中未定义localStorageService的原因。是的,您也不应添加到rootScope。您的工厂应如下所示:
angular.module('myApp', []).factory('localStorageService', function($rootScope){
this.go = function(task) {
var dataReceiver = localStorage.getItem('taskData');
var array = [];
var newArray = array.push({"title" : task});
if(dataReceiver === null) {
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
console.log(dataReceiver);
}
else {
array = JSON.parse(dataReceiver);
var newArray2 = array.push({"title" : task});
localStorage.setItem("taskData", JSON.stringify(array));
dataReceiver = JSON.parse(localStorage.getItem('taskData'));
for(var i = 0; i < newArray2; i++) {
console.log(dataReceiver[i].title);
}
}
return dataReceiver;
};
return this;
});
通过返回工厂对象,当将其及其所有方法注入到控制器中时,它们将可用。
关于javascript - 从服务到 Controller 获取变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24482965/