0

Trying to create a function that will remove the selected checkbox items from the array but can't seem to figure it out. I have tried using splice and .pop() but it just won't remove the items I select. I think the best way would be to use an if statement but I do not know how to write it so that it shows true or false. Please help!!!

JS:

.controller('toDoCtrl', function($scope, toDoFactory){ //set $scope variables $scope.tasks = toDoFactory.tasks; $scope.removeTasks = toDoFactory.removeTasks; }) .factory('toDoFactory', ['$http', function($http){ var toDo = { tasks: [], removeTasks: function(selectedTask){ angular.forEach(toDo.tasks, function(value, selectedTask){ var i = toDo.tasks.indexOf(value); toDo.tasks.splice(toDo.tasks.indexOf(i), 1); }); } }; return toDo; }]) 

HTML:

<button ng-click="removeTasks()">Remove</button> 
2
  • can you show us some more code?
    – Afsar
    CommentedFeb 6, 2016 at 8:43
  • you are finding wrong value you should find indexOf(selectedTask) and you are not passing selectedTask from calling of factory method.CommentedFeb 6, 2016 at 8:45

1 Answer 1

1

I did not really understood if you wanted to delete all selected tasks or just one. Anyway, you can do this for example :

JS:

app .controller('toDoCtrl', function($scope, toDoFactory){ //set $scope variables $scope.data = {}; $scope.data = toDoFactory.data; $scope.removeTasks = toDoFactory.removeTasks; $scope.removeTask = toDoFactory.removeTask; }) .factory('toDoFactory', ['$http', function($http){ var toDo = { data : { tasks: [ {text: "hello world", done: false}, {text: "hello world2", done: false}, {text: "hello world3", done: false} ] }, removeTasks: function(){ toDo.data.tasks = toDo.data.tasks.filter(function(task){ return !task.done; }); }, removeTask: function(index){ toDo.data.tasks.splice(index, 1); }, }; return toDo; }]); 

HTML:

 <body ng-controller="toDoCtrl"> <div ng-repeat='task in data.tasks'> <input type='checkbox' ng-model='task.done' /> <span>{{task.text}}</span> </div> <br/> <button ng-click="removeTasks()">Remove</button> </body> 

Plunkr : https://plnkr.co/edit/bTG0fEUZl1uoTIFT1NhC?p=preview

0

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.