javascript AngularJS 在页面加载时加载数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29828920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:07:44  来源:igfitidea点击:

AngularJS loading data on page load

javascriptangularjs

提问by Michael Freake

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.

我已经弄清楚如何在单击链接时加载和显示数据(请参阅fiddle),但无法弄清楚如何在页面加载时发生这种情况。

My thought is that I'm not using $scopeproperly or should be using a model.

我的想法是我没有$scope正确使用或应该使用模型。

Any help is appreciated.

任何帮助表示赞赏。

Code: http://jsfiddle.net/mikeyfreake/Lzgts/312/

代码:http: //jsfiddle.net/mikeyfreake/Lzgts/312/

回答by Shashank Agrawal

Just call the method $scope.loadFeeds()after defining the method itself.

只需$scope.loadFeeds()在定义方法本身后调用该方法即可。

回答by Mukund Kumar

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
    }]);

回答by Pankaj Parkar

Use ng-initdirective that will call exactly after controller gets loaded & make much more impact while testing a code using Karma & Jasmine.

使用ng-init指令控制器被加载和使更多的影响,同时测试使用噶&茉莉花代码后,将正好打电话。

Markup

标记

<div ng-controller="FeedController" ng-init="loadFeeds()">
  ..other html here
<div>

Fiddle Here

在这里小提琴



Though the better way would be calling loadFeedsmethod from controller at the end to ensure all the variables & methods have been initialized. You have to mock all the ajax response as mock data.

虽然更好的方法是loadFeeds在最后从控制器调用方法以确保所有变量和方法都已初始化。您必须将所有 ajax 响应模拟为模拟数据。