Angular.js使用过滤器从集合中删除项目

时间:2017-03-13 16:08:54

标签: angularjs angularjs-scope angular-filters angular-local-storage

我需要一些关于此代码的帮助,我需要存储"活动"并删除它。 目前它存储但不能删除。 (我只需要一个简单的解决方案)。

Angular.js

angular
.module("TodoList",["LocalStorageModule"])
.factory("TodoService", function(localStorageService){

    var todoService = {};
    todoService.key = "angular-todolist";

    if(localStorageService.get(todoService.key)){
        todoService.activities = localStorageService.get(todoService.key);
    } else {
        todoService.activities = [];
    }

    todoService.add = function(newActv){
        todoService.activities.push(newActv);
        todoService.updaLocalStorage();
    };

    todoService.updaLocalStorage = function(){
        localStorageService.set(todoService.key, todoService.activities);
    };

    todoService.clean = function(){
        todoService.activities = [];
        todoService.updaLocalStorage();
    };

    todoService.getAll = function(){
        return todoService.activities;
    };

    toDoService.removeItem = function (item) {   **Creating function for remove**
        toDoService.activities = toDoService.activities.filter(function (activity) {
            return activity !== item;
        });
        toDoService.updateLocalStorage();
        return toDoService.getAll();
    };

    return toDoService;
})
.controller("TodoListCtrl", function($scope, todoService){

    $scope.todo = todoService.getAll();
    $scope.newActv = {};
    $scope.addActv = function(){
        todoService.add($scope.newActv);
        $scope.newActv = {};
    }
    $scope.removeActv = function (item) {     **Scope for remove**
        $scope.todo = ToDoService.removeItem(item);
    }
    $scope.clean = function(){
        todoService.clean();
    }
});

HTML

<!DOCTYPE html>
<html ng-app = "TodoList">
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src = "todoctrl.js"></script>
    <script src = "angular-local-storage.min.js"></script>
</head>
<body ng-controller = "TodoListCtrl">
    <ul>
        <li ng-repeat = "actividad in todo">
            {{actividad.descripcion}} -
            {{actividad.fecha | date: 'short'}} -
            <a href="#" ng-click = "removeActv(actividad)" style="color:red">x</a>  **Where is removing**
        </li>
    </ul>
    <form ng-submit = "addActv()">
        <input type="text" ng-model = "newActv.descripcion">
        <input type="datetime-local" ng-model = "newActv.fecha"> 
        <input type="submit" value = "Guardar">
    </form>
    <button ng-click = "clean()">Limpiar</button>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

更新您的ToDoService.removeItem(item);功能。如果要从活动中删除项目,请使用array.splice(item)从阵列中删除项目。你想删除一个项目ToDoService.removeItem(item);,但你的功能不是这样做的。它返回的值为true或false。改变你的功能体。