so i am kinda new to angularjs and is facing a little difficulty with services. so i was working on an angularjs TO DO app and with services and can not get it working. This is my controller
.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;
}
});
THANK YOU IN ADVANCE
You can't use $scope inside a service like this.
See this answer: https://stackoverflow.com/a/22899880/3619813
You can not use $scope inside service. Check the Fiddle to understand how it should work.
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)
}
}]);
Below is the complete code.
.controller("myController", ['$scope','toDoService', function($scope,toDoService){
var lists = toDoService.getLists();
$scope.lists = lists;
$scope.add = function(){
toDoService.add($scope.lists);
}
Your service will look like below.
.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;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.