gpt4 book ai didi

javascript - 指令范围变量在 angularjs 中没有得到更新

转载 作者:行者123 更新时间:2023-12-02 15:21:26 25 4
gpt4 key购买 nike

我已经在指令中声明了一个 Controller 。我正在对数据列表执行添加和删除操作。但是当我在列表中添加数据时,范围全局变量没有得到更新。我正在使用该服务来获取数据。我的服务是// Angular 存储服务

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 Directive(指令) Controller 调用此服务。我的指令是

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)
};
}
};

});

当我添加待办事项时,它不会反射(reflect)在 $scope.todos 上。如果我们在函数内部更新它,那么它就会得到更新。但我认为它应该反射(reflect)函数外部的变化。

最佳答案

启动指令 Controller 时,只需设置 $scope.todos 一次。最好的选择可能是将 todoList 维护为存储服务中的公共(public)数组,并将 $scope.todos 指向它。否则,您需要在更改待办事项列表的每个函数中更新 $scope.todos。

关于javascript - 指令范围变量在 angularjs 中没有得到更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34015619/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com