Last Updated: 16 May 2016
Lab Length: 20 minutes
Objective
To implement the ability to toggle the completed state of a task.
Key Concepts:
- Calling REST update API
- Toggling an icon based on the state of data
Table of Contents
- 11.0: Adding Update to TasksService
- 11.1: Adding Update to the TasksController
- 11.2 Completing Tasks
- Wrap-up
11.0: Adding Update to TasksService
- Open the www/js/service/tasks.service.js file
We are going to add a new function called
updateTask. This function will take in the task object. It will then call the Back& API and update the data.function updateTask(task) { return $http({ method: 'put', url: Backand.getApiUrl() + '/1/objects/task/' + task.id, data: task }) .then(function (result) { return result; }); }Don’t forget to expose the updateTask to the service.
var service = { getTasks: getTasks, addTask: addTask, updateTask: updateTask };
11.1: Adding Update to the TasksController
- Open the www/js/controllers/tasks.controller file
We are going to add a new function called
updateTaskthat takes a parameter called task that will hold the task json object.function updateTask(task) { }Within the
updateTaskfunction we are going to set the completed value. Since it is a toogle for the completed state, we want to set it to the opposite of what it is currently set too. We are then going to call theTasksService.updateTaskfunction.function updateTask(task) { task.completed = !task.completed; TasksService.updateTask(task); }Now we need to expose the
updateTaskfunction to the viewvm.updateTask = updateTask;
11.2 Completing Tasks
- Open the www/templates/tasks.html file
On the checkmark icon we need to add another attribute called ng-click that calls vm.updateTask and passes in the task
<i class="icon" ng-class="task.completed ? 'ion-checkmark-circled': 'ion-ios-circle-outline'" ng-click="vm.updateTask(task)"> </i>
We are now ready to test the update functionality.
- If you don’t already have ionic serve running, open a command prompt and run the command ionic serve
- Select a project and when you click on the checkmark icon for a task it will toggle the completed state.