我的AngularJS应用程序中有一个搜索“页面”,它主要包含一个包含搜索表单(并显示结果)的视图和一个处理搜索请求的控制器。当用户键入搜索查询并点击“搜索”时,会调用$ scope.submit()方法,我可以正确查看结果。但是,当用户单击结果然后返回搜索页面时,它是空白的。我想到实现一个基于$ cookieStore的解决方案,以便查询存储在cookie中,每当用户返回搜索页面时,它会自动重新运行先前的搜索,这样他们就不必手动执行。问题是,模型更新(搜索从cookieStore值运行)但视图保持不变(空白)。这是我的控制器样本:
.controller('SearchCtrl', ['$scope', '$http', '$cookieStore','authService', function($scope, $http, $cookieStore, authService) {
var submitted = false;
$scope.submit = function(query){
$cookieStore.query = query;
submitted = true;
$http.jsonp(url).success(function(data) {
$scope.searchResults = data;
});
}
/*
Rerun query if user has pressed "back" or "home" button automatically:
*/
if(!submitted && $cookieStore.query){
console.log("submitting query from cookie store", $cookieStore.query);
$scope.submit($cookieStore.query);
}
... });
我尝试在自动搜索后使用$ scope。$ apply()但仍然没有快乐。该视图不会更新。你们可以给我任何提示吗?干杯
答案 0 :(得分:1)
您应该将$scope.$apply
放在回调函数的末尾。这是因为$http
进行异步AJAX调用,并且当响应返回时,Angular已经完成自动 - $applying
更改。因此,当您检查模型时,您会看到差异,但由于Angular不再是$applying
,因此无法在视图上看到差异。
因此,当您添加$scope.$apply
时,您将拥有以下内容:
.controller('SearchCtrl', ['$scope', '$http', '$cookieStore','authService', function($scope, $http, $cookieStore, authService) {
var submitted = false;
$scope.submit = function(query){
$cookieStore.query = query;
submitted = true;
$http.jsonp(url).success(function(data) {
$scope.searchResults = data;
$scope.$apply();
});
}
/*
Rerun query if user has pressed "back" or "home" button automatically:
*/
if(!submitted && $cookieStore.query){
console.log("submitting query from cookie store", $cookieStore.query);
$scope.submit($cookieStore.query);
}
... });