我很困惑为什么 ng-repeat 不显示搜索结果。什么有效:
发出 HTTP GET 请求以从数据库中获取所有数据,然后 ng-repeat 显示结果。
使用 a 发出 HTTP GET 请求以
searchterm
从数据库中获取部分数据,然后 ng-repeat 显示结果,并在控制器中$scope.searchterm = "acme";
设置。searchterm
我在模板中的搜索框将 发送
searchterm
到控制器,我可以在 console.log 中看到它,然后 HTTP GET 请求发出并返回正确的数据,我也可以在 console.log 中看到。
不起作用的是使用 ng-repeat 在模板中显示搜索结果数据。
这是我的 HTML 模板:
<div ng-controller="HomeController">
<form>
<label>Search: <input type="text" ng-model="searchterm" /></label><br />
<input type="submit" ng-click="search(searchterm)" value="Search" />
</form>
</div>
<div ng-repeat="network_operator in network_operators">
<span>{{network_operator.name}}</span><br />
</div>
这是我的控制器:
app.controller('HomeController', ['$scope', '$http', function($scope, $http){
console.log("Home controller.");
// This code displays all of the data, using ng-repeat in the template
// $http.get('http://qualifynow.herokuapp.com/products?searchstring=').then(function(response) {
// $scope.network_operators = response.data.products;
// console.log($scope.network_operators);
// }, function(response) {
// console.log("Error, no data returned.");
// });
// This works instead in place of the next line, the search results display with ng-repeat
// $scope.searchterm = "acme";
$scope.search = function(searchterm) { // This is the line that kills the ng-repeat
console.log($scope.searchterm); // This works, the search term is passed to the controller
$http.get('http://qualifynow.herokuapp.com/products?searchstring=supplier:' + $scope.searchterm).then(function(response) {
$scope.network_operators = response.data.products;
console.log($scope.network_operators); // The correct search results are logged
console.log($scope.network_operators[0].name); // The correct name is logged
}, function(response) {
console.log("Error, no data returned.");
});
};
}]);
我尝试运行$scope.apply()
,但这导致了一条$digest
已经在运行的错误消息。
$scope
该函数是否创建了一个新的存在$scope.search
?即,$scope
当我ng-repeat
试图在旧数据中查找数据时,我的数据是否愉快地驻留在新数据中$scope
?
我试过ng-submit
代替ng-click
,结果是一样的。
我尝试制作一个过滤器,效果很好,但是对于一个大型数据库,将所有数据放在上面$scope
然后过滤以获得搜索结果是没有意义的。只获取用户想要的数据会更快。