angularjs中没有更新指令作用域变量

Directive scope variable is not getting update in angularjs

本文关键字:指令 作用域 变量 更新 angularjs      更新时间:2023-09-26

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

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

});

当我添加todo项时,它不会反映在$scope.todos上。如果我们在函数中更新它,那么它就是在更新。但我认为它应该反映出功能之外的变化。

启动指令控制器时,只设置$scope.todos一次。最好的选择是将todoList维护为存储服务中的公共数组,并将$scope.todos指向它。否则,您需要在每个更改todo列表的函数中更新$scope.todos。