【发布时间】:2015-08-11 02:12:30
【问题描述】:
我正在尝试编写一些搜索输入代码,以使用 ngResource 从数据库中获取数据。
数据以 ng-repeat 显示在页面中,但是当我进行搜索并且 $scope 已更新时,视图未更新并显示旧数据。
代码如下:
main.html(活动视图)
<div ng-controller="searchCtrl as searchCtrl" layout="column">
<form class="form-inline search-form col-md-offset-1">
<div class="form-group col-md-5">
<label class="sr-only" for="search_location">Location</label> <input
id="search_location" type="search" class="form-control"
ng-Autocomplete ng-model="place" placeholder="Location" />
</div>
<div class="form-group col-md-5">
<label class="sr-only" for="search_tags">Tags</label> <input
style="width: 100%;" id="search_tags" type="search"
class="form-control" id="search_tags" placeholder="Tags">
</div>
<div class="col-md-1">
<md-button class="md-fab md-mini" aria-label="Search" ng-click="searchCtrl.search()"> <md-icon class="md-fab-center"
md-font-icon="glyphicon glyphicon-search" style="color: black;"></md-icon>
</md-button>
</div>
</form>
</div>
<div ng-controller="mainCtrl">
<div ng-repeat="evento in eventi" ng-include="'views/components/event_card.html'" class="col-md-3"></div>
</div>
main.js
'use strict';
app.factory('Eventi', function($resource) {
return $resource('/eventsws/events/:location', {location : '@location'}, {
search: {
method: 'GET',
params: {
'location' : "@location"
},
isArray : true
}
})
});
app.controller('mainCtrl', function($scope, Eventi) {
$scope.eventi = Eventi.query();
});
搜索栏.js
'use strict';
app.controller('searchCtrl', function($scope, Eventi) {
$scope.place = null;
this.search = function() {
$scope.eventi = Eventi.search({
'location' : $scope.place
});
}
});
当它启动时,它会从数据库中获取所有数据并正确显示它们,当我尝试进行搜索时,$scope.eventi 会更新(我可以从调试中看到 $scope.eventi 中的新数据)但是视图仍然显示旧数据并且永远不会更新。
我尝试在搜索功能的末尾使用 $scope.$apply 但结果是一样的。
你知道为什么它不工作吗?
感谢您的宝贵时间。
【问题讨论】:
-
您在调试中看到的 $scope.eventi 是您的 searchCtrl 中的那个,而不是您的 mainCtrl 中的那个。要更新您的 mainCtrl $scope.eventi,您必须找到其他方法。 (一个干净但冗长的解决方案是使用服务来共享控制器中的变量,一个奇怪但简短的解决方案是使用 $broadcast 和 $on)。如果您想了解如何在控制器之间共享服务数据的清晰示例,请随时询问。但是在 plunker 中构建它需要一些时间。
-
谢谢,我试过了,我可以看到我用服务定义的共享属性,我现在打破 mainCtrl 来仔细检查那个控制器的 $scope,我可以看到它更新了,但视图仍然显示旧数据:(
标签: angularjs angularjs-ng-repeat ngresource