Reputation: 3156
I have declared a controller in directive. I am performing add and remove operation on the list of data. But when i add the data in list the scope global variable is not getting update. I am using the service to get data. My service is // an angular storage service
var storageService = angular.module('storageService', [])
.service('storage', function(){
var todoKey = "todo_data";
this.getTodos = function(){
todolist = (localStorage.getItem(todoKey)!==null)?JSON.parse(localStorage.getItem(todoKey)) : [];
return todolist
}
this.addTodo = function(taskName){
console.log("storage"+ taskName.text);
todoList = this.getTodos()
console.log(todoList);
todoList.push(taskName);
console.log(todoList);
localStorage.setItem(todoKey, JSON.stringify(todoList));
}
this.removeTodo = function(taskName){
var todoList = this.getTodos();
todoList.splice($.inArray(taskName, todoList), 1);
localStorage.setItem(todoKey, JSON.stringify(todoList));
}
this.completeTodo = function(task){
task.completed = true;
}
});
I am calling this service through angular directive controller.My directive is
app.directive("todoList", function(){
return{
restrict: 'E',
replace: 'true',
templateUrl: 'partial_template/todolist.html',
controller: function($scope, $element, storage){
$scope.todos = storage.getTodos();
$scope.addTodo = function(taskName) {
task = new TODO.task(taskName);
storage.addTodo(task);
// create new object
$scope.taskName = "";
};
$scope.removeTodo = function(taskName){
// remove the task from the todolist
storage.removeTodo(taskName);
};
$scope.completeTodo = function(taskName){
// change the status of the task
storage.completeTodo(task)
};
}
};
});
When i add todo item it doesn't not reflect on $scope.todos. If we update it inside the function then it is getting update.But i think it should be reflect the change outside the function.
Upvotes: 0
Views: 62
Reputation: 2553
You only set $scope.todos once when initiating your directive controller. The best option could be to maintain todoList as a public array in storage service and point $scope.todos to it. Otherwise you need to update $scope.todos in every function where you change list of todos.
Upvotes: 2