我在我的AngularJS应用程序中有一个搜索“页面”,它本质上由一个保存搜索表单(并显示结果)的视图和一个处理搜索请求的控制器组成。当用户输入搜索查询并点击' search‘时,$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(),但仍然没有效果。视图就是不会更新。你们能给我点提示吗?干杯
发布于 2014-01-28 00:41:43
您应该将$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);
}
... });https://stackoverflow.com/questions/21385749
复制相似问题