1

When an item in the list is clicked, an ng-click fires with the id of the item sent, the idea was to get the description of the item to match the id but it seems to only be picking up the index of the item instead.

Plnk

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $http) {
  $scope.name = 'World';
  $http.get('tasks.json').success(function(data) {
               $scope.tasks = data.item;
                console.log($scope.tasks);
            });

            $scope.viewTask = function(id) {
              console.log(id);
              console.log($scope.tasks[id].description); //The Description to go with the ID.
            };
});

1 Answer 1

2

You are returning the task with index of id. It sounds like you want to search the array for the task with a certain id and return that one's description. Something like:

  $scope.viewTask = function(id) {
          console.log(id);
          for(i=0;i<$scope.tasks.length;i++) {
             if ($scope.tasks[i].id == id) {
                 console.log($scope.tasks[id].description);
             } 
          }

 };

You could create a filter or something to make this easier but the logic is the same. There are several answers here that would help with a filter so as to not duplicate code:

In Angular, I need to search objects in an array

In this case your function would look l ike:

$scope.viewTask = function(id) {
          console.log(id);
          var found = $filter('getById')($scope.tasks, id);
          console.log(found.description);
 };

Plunker: http://plnkr.co/edit/UMApcLbzz0HZIKkRrnOQ?p=preview

I modified the answer to log the data like your question.

Sign up to request clarification or add additional context in comments.

1 Comment

I went for this var found = $filter('filter')($scope.tasks, {id: task_id}, true); if (found.length) { found[0].description; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.