【发布时间】:2017-06-09 22:20:06
【问题描述】:
我很困惑为什么 ng-repeat 不显示搜索结果。什么有效:
发出 HTTP GET 请求以从数据库中获取所有数据,然后 ng-repeat 显示结果。
使用
searchterm发出HTTP GET 请求以从数据库中获取部分数据,然后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.search 函数是否正在创建新的$scope?即,当ng-repeat 试图在旧的$scope 中查找数据时,我的数据是否愉快地驻留在新的$scope 中?
我试过ng-submit而不是ng-click,结果是一样的。
我尝试制作一个过滤器,效果很好,但是对于大型数据库,将所有数据放在$scope 上然后过滤以获取搜索结果是没有意义的。只获取用户想要的数据会更快。
【问题讨论】:
-
用 $timeout 包裹 $scope.apply(),你不会得到摘要错误
标签: javascript angularjs angularjs-1.6