2

I'm using a $http get request in my angular application to access data to bind to my view in a loop using ng-repeat and a filter based on a users input value for a simple search. I'm able to access the data and filter and bind the results to my view but the search only happens when the second character the user types is on keyup, not the first character. I want my search to happen on the first keyup.

MY CONTROLLER:

angular.module("app.findfriendsApp").controller("FindfriendsCtrl", [
  '$scope', '$http',
  ($scope, $http)->

    # Get Request.
    $http.get('find_friends.json').success((data, status, headers, config)->
      $scope.friends = data;
    ).error((data, status, headers, config)->
      log error
    )

])

MY VIEW:

main ng-app="app.findfriendsApp"
  .container ng-controller="FindfriendsCtrl"
    .row
      .col-xs-12
        input[type="text" 
              ng-model="search" 
              placeholder="Search by Name"]

      .col-xs-12
        ul 
          li[ng-repeat="friend in filteredData = (friends | filter:search)" 
             ng-hide="filteredData.length==friends.length"] 
               |{{friend.username}}
  • I've created a fiddle: http://jsfiddle.net/4837n5rq/ But was unable to replicate your error? I even added a delay to the ajax. If you enter text in the input before the AJAX returns it will still filter when it does return. If you wait for the AJAX to return it will still filter on the first key press, and every after. Could there be anything in the code you haven't posted causing issues? – ste2425 Sep 11 '15 at 11:02
  • I think it might have something to do with the $http request because when I setup a regular array in the controller it loops and searches on the first keyup. –  Sep 11 '15 at 11:31
  • I figured out the problem. There was no problem with the logic, just an error in how I expected it to behave. The script hides data when the filtered length is the same as the original length..."E" is a very common vowel and apparently it was in every returned data. I was typing "E" and it remained hidden. Problem solved. –  Sep 11 '15 at 15:22
  • Additionally, I'm new to angular, and I thought the ng-repeat loop only loops over the specific item. Apparently it's looping over all the values in each object. –  Sep 11 '15 at 15:33
  • 1
    Gad you sorted it, yes `ng-repeat` will loop over every element in an array or over every property in an object if using `ng-repeat="(key, val) in myObject"`. When using the pipes to chain filters it will run from left to right through each filter, the output of the last filter will be what is looped over and provided to your view template. – ste2425 Sep 12 '15 at 13:50

0 Answers0