Angular JS服务无法工作
Angular JS services not working
所以我对angularjs有点陌生,并且在服务方面面临一些困难。所以我正在做一个angularjs TO DO应用程序和服务,不能让它工作。这是我的控制器
.controller("myController", ['$scope','toDoService', function($scope,toDoService){
var lists = toDoService.getLists();
$scope.lists = lists;
$scope.add = function(){
// WHAT TO PUT HERE????
}
and this is my service
.service('toDoService', function(){
this.getLists =function(){
var list = [
{"name" : "abebe" ,"done":false, id: Date.now()}
];
return list;
}
this.add = function(){
$scope.lists.push({'name':$scope.nameSpace,'done':false, id: Date.now()});
$scope.nameSpace = '';
return this;
}
});
提前致谢
你不能在这样的服务中使用$scope
查看答案:https://stackoverflow.com/a/22899880/3619813
你不能在service中使用$scope。检查Fiddle以了解它应该如何工作。
myApp.service('toDoService', function(){
this.details = {
lists: [
{"name" : "abebe" ,"done":false, id: Date.now()}
]
}
this.getLists =function(){
var list = [
{"name" : "abebe" ,"done":false, id: Date.now()}
];
return list;
}
this.addList = function(item) {
this.details.lists.push(item)
}
});
myApp.controller("myController", ['$scope','toDoService',
function($scope,toDoService){
$scope.lists = function() { return toDoService.details.lists };
$scope.add = function(){
// WHAT TO PUT HERE????
var newListItem = {"name" : "abebe" ,"done":false, id: Date.now()}
toDoService.addList(newListItem)
}
}]);
下面是完整的代码。
.controller("myController", ['$scope','toDoService', function($scope,toDoService){
var lists = toDoService.getLists();
$scope.lists = lists;
$scope.add = function(){
toDoService.add($scope.lists);
}
您的服务将如下所示:
.service('toDoService', function(){
this.lists = [];
this.getLists =function(){
var list = [
{"name" : "abebe" ,"done":false, id: Date.now()}
];
return list;
}
this.add = function(data){
lists.push(data);
return lists;
}
});
相关文章:
- angular2中的全局服务不工作
- fetch事件处理程序中的fetch()未触发服务工作程序中的fetch事件
- JQuery-HTML到PDF没有'无法在IE中工作(来自C#asmx Web服务)
- 序列化方向结果到 JSON 发送到我的网络服务无法正常工作
- 服务工作线程是否可以响应同步 XHR 请求
- 增加服务工作线程的生命周期
- 角度工厂和服务工作,但不如预期
- 忽略服务工作进程请求中的查询参数
- 了解服务工作进程范围
- 角度服务无法正常工作
- 使用服务跟踪用户状态并使 $watch() 正常工作
- iOS 移动 Safari 服务工作进程缓存限制
- 服务工作线程是否可以缓存 POST 请求
- 注册服务工作进程返回中止错误代码:20
- AngularJS模态服务停止工作
- 回调如何在 AngularJS 调用 REST 服务中工作
- Angular JS:使用 $http.get() 导入 JSON 数据 - 在控制器中工作,不在服务中 - 为什么
- Angular$route服务没有;t被按时注入到控制器中——最初在页面加载时未定义,但后来一切都像符咒一样工作
- 如何设置服务以传递谷歌工作表ID?AngularJS
- ajax GET无法工作(服务数据无法获取)