我是Angular的新手并开始构建RSS-Feed应用程序。当用户点击Feed链接时,我想填充列出所有Feed条目的视图。我有一个FeedsCtrl(显示提要标题),一个EntriesCtrl(显示与提要相关的所有条目),以及用于在两者之间进行通信的服务。
问题是当用户点击Feed链接时,我无法让EntriesCtrl更新视图。以下是我所拥有的快照:
feeds.html.erb:
<div class="feed-index-wrapper" ng-controller="FeedsCtrl">
<ul class="feed-group list-group">
<li class="list-group-item"
ng-repeat="feed in feeds">
<a ng-click="fetchEntries(feed.id)">{{ feed.title }}</a>
</li>
</ul>
</div>
&#13;
entries.html.erb:
<div class="entries-index-wrapper" ng-controller="EntriesCtrl">
<ul class="entry-group list-group">
<li class="list-group-item"
ng-repeat="entry in entries">
{{ entry.title }}
</li>
</ul>
</div>
&#13;
服务/ feed.js:
App.factory('Feed', ['$resource', function($resource){
return $resource('/api/feeds/:id', { id: '@id' })
}]);
&#13;
服务/ entry.js:
App.service('Entry', ['$resource', function($resource){
return {
preview: [{ title: "Preview "}],
resource: $resource('/api/feeds/:id/entries', { id: '@id' }),
}
}]);
&#13;
控制器/ feeds_ctrl.js:
App.controller('FeedsCtrl', function($scope, Feed, Entry) {
$scope.feeds = Feed.query();
$scope.fetchEntries = function(id) {
Entry.resource.query({ id: id }, function(entries) {
Entry.preview = entries;
});
}
});
&#13;
控制器/ entries_ctrl.js:
App.controller('EntriesCtrl', function($scope, Entry) {
$scope.entries = Entry.preview;
});
&#13;
app.js:
App = angular.module('TheDailyRead', [
'ngResource',
'ui.router',
'templates',
'ngRoute'
]);
App.config(function($routeProvider, $stateProvider, $locationProvider) {
$routeProvider.otherwise('/');
$stateProvider
.state('feeds', {
url: '/',
views: {
'': {
templateUrl: 'feeds.html',
controller: 'FeedsCtrl',
},
'new-feed': {
templateUrl: 'new.html',
controller: 'NewFeedCtrl',
},
'entries': {
templateUrl: 'entries.html',
controllers: 'EntriesCtrl'
}
}
});
$locationProvider.html5Mode(true);
});
&#13;
我尝试过使用Stack Overflow的其他答案解决方案,但是没有多少运气。有什么建议吗?
答案 0 :(得分:0)
Entry.preview = entries;
中调用function $scope.fetchEntries
并传递相应的数据。Entry.preview = entries;
希望它有所帮助!
P.S。如果它没有帮助,请尝试$ scope。$ watch,在AngularJS Documentation中阅读更多内容
答案 1 :(得分:0)
您需要更新服务调用回调($scope.entries = Entry.preview
)中的范围条目,因此:
App.controller('FeedsCtrl', function($scope, Feed, Entry) {
$scope.feeds = Feed.query();
$scope.fetchEntries = function(id) {
Entry.resource.query({ id: id }, function(entries) {
Entry.preview = entries;
});
}
});
应该成为这个:
App.controller('FeedsCtrl', function($scope, Feed, Entry) {
$scope.feeds = Feed.query();
$scope.fetchEntries = function(id) {
Entry.resource.query({ id: id }, function(entries) {
$scope.entries = Entry.preview = entries; // <--- here
// force a scope digest if needed
$scope.apply();
});
}
});
答案 2 :(得分:0)
可能不是最优雅的方式,但我能够通过抓住包含条目控制器的div类并访问该div的范围来实现此功能。像这样:
App.controller('FeedsCtrl', function($scope, Feed, Entry) {
$scope.feeds = Feed.query();
$scope.fetchEntries = function(id) {
Entry.resource.query({ id: id }, function(entries) {
var entriesWrapper = $('.entries-index-wrapper').scope();
Entry.preview = entriesWrapper.entries = entries;
});
}
});