Search box in angular js

后端 未结 5 650
谎友^
谎友^ 2021-01-30 09:09

I want to implement a search box in my angularJs application. As soon as user starts typing some name in the search box , some REST service should be called and it should fetch

5条回答
  •  春和景丽
    2021-01-30 09:50

    You should define a directive that listen onkeypress.

    app.directive('myOnKeyDownCall', function () {
        return function (scope, element, attrs) {
            element.bind("keydown keypress", function (event) {            
                    scope.$apply(function (){
                        scope.$eval(attrs.ngEnter);
                    });
                    event.preventDefault();
            });
        };
    });
    

    HTML

        
    

    CONTROLLER

    $scope.callRestService= function() {
      $http({method: 'GET', url: '/someUrl'}).
        success(function(data, status, headers, config) {
             $scope.results.push(data);  //retrieve results and add to existing results
        })
    }
    

    Would be nice to wait until 3 keys has been typed, for that in directive:

    var numKeysPress=0;
    element.bind("keydown keypress", function (event) {   
             numKeysPress++;
                 if(numKeysPress>=3){
                    scope.$apply(function (){
                        scope.$eval(attrs.myOnKeyDownCall);
                    });
                    event.preventDefault();
                  }
            });
    

    Perhaps, exists typeahead directive from angular-ui that you can use: angular-ui typeahead I hope it helps you

提交回复
热议问题