繁体   English   中英

指令范围变量未在angularjs中更新

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM