Javascript 指令作用域变量未在angularjs中获得更新
我已经在指令中声明了一个控制器。我正在对数据列表执行添加和删除操作。但当我在列表中添加数据时,scope全局变量没有得到更新。我正在使用该服务获取数据。 我的服务是 //角存储服务Javascript 指令作用域变量未在angularjs中获得更新,javascript,angularjs,Javascript,Angularjs,我已经在指令中声明了一个控制器。我正在对数据列表执行添加和删除操作。但当我在列表中添加数据时,scope全局变量没有得到更新。我正在使用该服务获取数据。 我的服务是 //角存储服务 var storageService = angular.module('storageService', []) .service('storage', function(){ var todoKey = "todo_data"; this.getTodos = function(){
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指令控制器调用此服务。我的指令是
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上。如果我们在函数内部更新它,那么它将得到更新。但是我认为它应该反映函数外部的更改 启动指令控制器时,只需设置$scope.todos一次。最好的选择是将todoList作为存储服务中的公共阵列进行维护,并将$scope.todos指向它。否则,您需要在更改TODO列表的每个函数中更新$scope.todo。正如@SSH在其回答中所说,您实际上并没有更改任何函数中的
$scope.todo
数组。在应用程序启动时,您已经从存储
中读取了值,对存储的任何更改都不是对$scope.todos的更改,除非您读取本地存储并再次通过JSON解析器对其进行解析。我正在将addTodo绑定到scope,而不是当scope检测到将自动反映更改的更改时。