[英]AngularJS loading data on page load
I'm new to AngularJS and trying to setup an app that reads an RSS feed and displays the items upon page load. 我是AngularJS的新手,并尝试设置一个应用程序来读取RSS源并在页面加载时显示这些项目。
I have figured out how to have the data loaded and displayed upon clicking a link (see fiddle ), but can't figure out how to have this happen on page load. 我已经弄清楚如何在点击链接时加载和显示数据(请参阅小提琴 ),但无法弄清楚如何在页面加载时发生这种情况。
My thought is that I'm not using $scope
properly or should be using a model. 我的想法是我没有正确使用$scope
或者应该使用模型。
Any help is appreciated. 任何帮助表示赞赏。
Code: http://jsfiddle.net/mikeyfreake/Lzgts/312/ 代码: http : //jsfiddle.net/mikeyfreake/Lzgts/312/
在定义方法本身之后,只需调用方法$scope.loadFeeds()
。
you have not called your controller function. 你还没有调用你的控制器功能。 just use this code for controller: 只需将此代码用于控制器:
var app = angular.module('newsFeed', []);
app.controller('FeedController', ['$scope', 'FeedService', function ($scope, Feed) {
console.log('FeedController called.');
//These calls cause errors:
//$scope.loadFeeds();
//loadFeeds();
//this.loadFeeds();
//loadFeeds();
$scope.loadFeeds = function () {
console.log('loadFeeds called.');
Feed.parseFeed('http://www.rotoworld.com/rss/feed.aspx?sport=nfl&ftype=article&count=12&format=atom').then(function (res) {
$scope.rotoWorld = res.data.responseData.feed.entries;
});
};
$scope.loadFeeds();//you have leave this line pf code
}]);
Use ng-init
directive that will call exactly after controller gets loaded & make much more impact while testing a code using Karma & Jasmine. 使用ng-init
指令,它将在控制器加载后完全调用,并在使用Karma和Jasmine测试代码时产生更大的影响。
Markup 标记
<div ng-controller="FeedController" ng-init="loadFeeds()">
..other html here
<div>
Though the better way would be calling loadFeeds
method from controller at the end to ensure all the variables & methods have been initialized. 虽然更好的方法是在结束时从控制器调用loadFeeds
方法,以确保所有变量和方法都已初始化。 You have to mock all the ajax response as mock data. 您必须将所有ajax响应模拟为模拟数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.