Angularjs instant search doesn't work as supposed

148 views Asked by At

I am trying to code a simple Angularjs instant search form. Here is a bit of code with which i work:

<script language="javascript">

 // The controller for instant search with Angular
 function InstantSearchController($scope)
  {
  $scope.items = [{ip:'144.76.24.100'},{ip:'176.9.56.120'},{ip:'178.63.240.111'};
  $scope.qq = '';
  $scope.show_results = false;

  // Paste the clicked value into the search box
  $scope.pasteValue = function(val)
   {
   $scope.qq = val;
   document.getElementById('q').value = val;
   $scope.show_results = false; 
   }

  // Paste the clicked value into the search box
  $scope.showResults = function(e)
   {
   e.stopPropagation();
   $scope.show_results = true;
   }
  }
 </script>


<label>Search for <input type="text" name="q" id="q" ng-value="{{qq}}" value="{{qq}}" size="23" ng-model="searchString" ng-click="showResults($event)">
 <div ng-show="show_results">
 <ul>
  <li ng-repeat="i in items | searchFor:searchString">
   <div ng-click="pasteValue(i.ip)">{{i.ip}}</div>
  </li>
 </ul>
 </div>
</label>

My problems are:

  1. When a search result from the "LI" tag is clicked, it has to be pasted into the search box (that is working) and all search results (the entire "DIV" with "UL") must hide (that doesn't work).

  2. Currently the value of the search box is set with the "document.getElementById('q').value = val;" line. I added that line because the previous one "$scope.qq = val;" does not work with this bit of code. I believe that Angularjs has some way to set the value.

Thank you.

1

There are 1 answers

4
Pankaj Parkar On

Your pasteValue function should not set value of input using JavaScript that would messed up digest cycle and binding will not update, you should point to $scope.

// Paste the clicked value into the search box
$scope.pasteValue = function(val)
{
    $scope.searchString = val; //will update filter
    $scope.show_results = false; 
}