Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a search in real time with angularjs

Tags:

ajax

angularjs

I want to create a simple real-time search with angularjs client side, and java server side, i want to use the similar effect than onKeyUp in dom and ajax but in angular js,

   <div ng-app="MyModule" ng-controller="MainCtrl">                     
                <input class="form-control field span12" id="objctf" rows="4" ng-model="keywords" />
                <a href="/adminpanel?q=" class="btn btn-primary">Manage</a>
                <div>
                  <p ng-show="loading">Loading...</p>
                  <p ng-hide="loading">Response: {{response}}</p>
                  <p ng-hide="loading">writed: {{keywords}}</p>
                </div>
    </div>


var MainCtrl = function($scope, $http) {

$scope.keywords = "debut";
alert ('en mode ajax '+$scope.keywords);
$scope.response = $http.post('/api/member/getuser', { "username" : $scope.keywords });

};

like image 968
darkman Avatar asked Jul 21 '14 15:07

darkman


2 Answers

Add ng-change to your input like so:

<input class="form-control field span12" id="objctf" rows="4" ng-model="keywords" ng-change="search()" />

Create a method to handle the change on the controller:

myApp.controller('someCtrl', ['$scope', 'someService', function($scope, someService){    
    $scope.search = function(){
        someService.search($scope.keywords).then(function(response){
            $scope.response = response.data;
        });
    };

}]);

Finally, create a service to make the call to the server:

myApp.service('someService', ['$http', function($http){
    return {
        search: function(keywords){
            return $http.post('/api/member/getuser', { "username" : keywords });
        }
    }
}]);

Handling things in this fashion, you'll gain a re-usable search method whose results can be persisted through routes if needs be.

like image 140
m.casey Avatar answered Oct 30 '22 00:10

m.casey


myApp.controller('someCtrl', ['$scope', 'someService', function($scope, someService){    
$scope.search = function(){
    someService.search($scope.keywords).success(function(response){
        $scope.response = response.data;
    }).error(function(){
        console.log('error');
    });
};}]);

Replace .then by .success and .error ;) @jack

like image 22
ZelkiN Avatar answered Oct 29 '22 23:10

ZelkiN