我正在尝试用AngularJS创建一个实时搜索函数。我有一个输入字段:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
它可以在范围内传递搜索关键字,这样我就可以执行实时搜索(JS),并将结果直接显示给DOM。
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
发布于 2014-09-07 15:30:47
在角度控制器内部使用一个手表表达式。
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
发布于 2014-09-07 15:14:03
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});
发布于 2014-09-07 15:43:43
你可以像贾斯汀约翰提议的那样使用手表,也可以在使用ng-change
时使用ng-change
,你的控制器应该如下所示
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
和你的html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
https://stackoverflow.com/questions/25711642
复制相似问题