سؤال

I am creating a small todo app to learn Angular. I am stuck in one place. My task will be listed as list of links. Each time user clicks on it its status should change. So when a user clicks on a task its status becomes, doing. Then in next click it become done. And one click makes it later. This should also reflect be stored back to the $scope from where this loaded. I have no idea, what will be the best way to do this in Angular.

Right now I have $scope.tasks storing all the tasks and $scope.tasks.$status is holding the available stasuses.

var app = angular.module("app");

app.controller('Ctrl', function($scope) {
$scope.tasks = [
    {id: 1, text: 'Do something.', status: 'doing'},
    {id: 2, text: 'Undo that thing.', status: 'done'},
    {id: 3, text: 'Redo it again.', status: 'started'},
    {id: 4, text: 'Responsive', status:'later'}
  ];

  $scope.tasks = {
    status: ['doing','done', 'later' ]
  };

 $scope.clicked = function() {

  //some logic.        

 };

}

Below is the html.

<div ng-app="app" ng-controller="Ctrl" class"container">
 <div ng-repeat="task in tasks" >
    <li>
       <a href="#"  ng-click="clicked()" id="{{task.id}}">
        {{task.text}} - {{task.status}}
       <a/>
    </li>
 </div>

</div>

Is whatever I done so far correct? What is the best approach to toggle through the options? Is there any functions for that?

هل كانت مفيدة؟

المحلول

There're tons of solutions depending on what you want to do with this next. The simplest one seems to be:

$scope.clicked = function(task){
  task.status = nextStatus(task.status);
};
function nextStatus(st){
  return $scope.statuses[$scope.statuses.indexOf(st) + 1];
}

Note that you also should pass task to the function:

<a ng-click='clicked(task)'>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top