1

How do you get a single item from a GoInstant GoAngular collection? I am trying to create a typical show or edit screen for a single task, but I cannot get any of the task's data to appear.

Here is my AngularJS controller:

.controller('TaskCtrl', function($scope, $stateParams, $goKey) {

    $scope.tasks = $goKey('tasks').$sync();

    $scope.tasks.$on('ready', function() {
        $scope.task = $scope.tasks.$key($stateParams.taskId);
        //$scope.task = $scope.tasks.$key('id-146b1c09a84-000-0'); //I tried this too
    });
});

And here is the corresponding AngularJS template:

<div class="card">
    <ul class="table-view">
        <li class="table-view-cell"><h4>{{ task.name }}</h4></li>
    </ul>
</div>

Nothing is rendered with {{ task.name }} or by referencing any of the task's properties. Any help will be greatly appreciated.

Corey Quillen
  • 1,566
  • 4
  • 24
  • 52

1 Answers1

4

You might handle these tasks: (a) retrieving a single item from a collection, and (b) responding to a users direction to change application state differently.

Keep in mind, that a GoAngular model (returned by $sync()) is an object, which in the case of a collection of todos might look something like this:

{  
    "id-146ce1c6c9e-000-0": { "description": "Destroy the Death Start" },
    "id-146ce1c6c9e-000-0": { "description": "Defeat the Emperor" }
}

It will of course, have a number of methods too, those can be easily stripped using the $omit method.

If we wanted to retrieve a single item from a collection that had already been synced, we might do it like this (plunkr):

$scope.todos.$sync();

$scope.todos.$on('ready', function() {
  var firstKey = (function (obj) {
    for (var firstKey in obj) return firstKey;
  })($scope.todos.$omit());

  $scope.firstTodo = $scope.todos[firstKey].description;
});

In this example, we synchronize the collection, and once it's ready retrieve the key for the first item in the collection, and assign a reference to that item to $scope.firstTodo.

If we are responding to a users input, we'll need the ID to be passed from the view based on a user's interaction, back to the controller. First we'll update our view:

  <li ng-repeat="(id, todo) in todos">
      <a href="#" ng-click="whichTask(id)">{{ todo.description }}</a>
  </li>

Now we know which todo the user want's us to modify, we describe that behavior in our controller:

$scope.todos.$sync();

$scope.whichTask = function(todoId) {
  console.log('this one:', $scope.todos[todoId]);

  // Remove for fun
  $scope.todos.$key(todoId).$remove();
}

Here's a working example: plunkr. Hope this helps :)

Slukehart
  • 1,037
  • 5
  • 15