我想用angularjs客户端和java服务器端创建一个简单的实时搜索,我想在dom和ajax中使用与onKeyUp类似的效果,但是在角度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 });
};
答案 0 :(得分:11)
将ng-change添加到您的输入中,如下所示:
<input class="form-control field span12" id="objctf" rows="4" ng-model="keywords" ng-change="search()" />
创建一个方法来处理控制器上的更改:
myApp.controller('someCtrl', ['$scope', 'someService', function($scope, someService){
$scope.search = function(){
someService.search($scope.keywords).then(function(response){
$scope.response = response.data;
});
};
}]);
最后,创建一个服务来调用服务器:
myApp.service('someService', ['$http', function($http){
return {
search: function(keywords){
return $http.post('/api/member/getuser', { "username" : keywords });
}
}
}]);
以这种方式处理事物,您将获得一种可重复使用的搜索方法,如果需要,其结果可以通过路径保留。
答案 1 :(得分:1)
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');
});
};}]);
用.success和.error替换.then;)@jack