[英]Directive scope variable is not getting update in angularjs
我已經在指令中聲明了控制器。 我正在對數據列表執行添加和刪除操作。 但是,當我在列表中添加數據時,范圍全局變量沒有得到更新。 我正在使用該服務來獲取數據。 我的服務是//角度存儲服務
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;
}
});
我通過角度指令控制器調用此服務。我的指令是
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)
};
}
};
});
當我添加待辦事項時,它不會反映在$ scope.todos上。 如果我們在功能內部更新它,那么它正在更新。但是我認為它應該反映功能外部的變化。
啟動指令控制器時,只需將$ scope.todos設置一次。 最好的選擇是將todoList保持為存儲服務中的公共數組,並將$ scope.todos指向它。 否則,您需要在更改待辦事項列表的每個函數中更新$ scope.todos。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.