How to create a search in real time with angularjs

2020-06-16 02:09发布

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 });

};

2条回答
干净又极端
2楼-- · 2020-06-16 02:28
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

查看更多
beautiful°
3楼-- · 2020-06-16 02:44

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.

查看更多
登录 后发表回答