我在指令中声明了一个控制器。我正在对数据列表执行添加和删除操作。但是当我在list中添加数据时,作用域全局变量并没有得到更新。我正在使用该服务来获取数据。我的服务是//一个角度存储服务
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;
}
});
我通过angular指令调用这个服务controller.My指令是
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)
};
}
};
});
当我添加todo项时,它不会不反映在$scope.todos上。如果我们在函数内部更新它,那么它就会得到update.But,我认为它应该反映函数外部的变化。
发布于 2015-12-01 08:22:55
在启动指令控制器时,只需设置一次$scope.todos。最佳选择可能是将todoList作为存储服务中的公共阵列进行维护,并将$scope.todos指向它。否则,您需要在每个更改待办事项列表的函数中更新$scope.todos。
https://stackoverflow.com/questions/34015619
复制相似问题