Search with javascript

2

I have a search engine that has the problem:  - Returns all values of a list, when deleted element of the search field, the expected is that if only the initial elements return, not all. This is the search function I'm using:

$scope.$watch('q', function (newValue, oldValue) {
        if (oldValue != null) {
        $http.get('/api/services.json?q=' + newValue)
          .success(function (data) {
              $scope.services = data;
                      });
      };
      if (oldValue == null){
          $http.get('/api/services.json?q=' + oldValue)
            .success(function (data) {
              $scope.services = data;
               });
      }

    }, true);
    
asked by anonymous 25.10.2016 / 18:00

1 answer

1

Ideally, you should filter your server search to consume no resource. But if you want to limit the number of records in AngularJS you can use the limitTo :

limitTo

  

Creates a new array or string containing only the specified number of elements. Elements are taken from the beginning or end of the array base, string or number , as specified by the value and sign (positive or negative) of the limit.

Use is given by:

HTML

{{ limitTo_expression | limitTo : limit : begin}}

Javascript

$filter('limitTo')(input, limit, begin)

Your example would look like

$scope.services = $filter('limitTo')(data, 5, 0);

Functional example:

(function() {
  'use strict';

  angular
    .module('appExemploLimitado', []);

  angular
    .module('appExemploLimitado')
    .controller('LimiteController', LimiteController);

  LimiteController.$inject = ['$filter'];

  function LimiteController($filter) {
    var limite = this;
    
    iniciar();
    
    function iniciar() {
      limite.registros = [];
      limite.registros.push('Registro 1');
      limite.registros.push('Registro 2');
      limite.registros.push('Registro 3');
      limite.registros.push('Registro 4');
      limite.registros.push('Registro 5');
      limite.registros.push('Registro 6');
      limite.registros.push('Registro 7');
      limite.registros.push('Registro 8');
      limite.registros.push('Registro 9');
      limite.registros.push('Registro 10');

      limite.maximo = 5;
    }
  }
})()
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"type="text/javascript"></script>

<div ng-app="appExemploLimitado">
  <div ng-controller="LimiteController as limite">
    Máximo de registros: <input type="number" name="input" ng-model="limite.maximo" min="1" max="10" required>
    <div ng-repeat="registro in limite.registros | limitTo:limite.maximo:0">
        <h3>{{registro}}</h3>
      </div>
  </div>
</div>
    
24.11.2016 / 01:18