AngularJS load data on page load

I am new to AngularJS and am trying to customize an application that reads an RSS feed and displays elements when the page loads.

I figured out how to load and display data when a link is clicked (see fiddle ), but cannot figure out how this happens when a page loads.

I thought I was not using $scopecorrectly or should use the model.

Any help is appreciated.

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

+4
source share
3 answers

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

+5
source

. :

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

Use a directive ng-initthat is called exactly after the controller is loaded and will have a much greater impact when testing code using Karma and Jasmine.

Markup

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

Script here


Although the best way would be to call a method loadFeedsfrom the controller at the end to ensure that all variables and methods have been initialized. You should mock the whole ajax answer as false data.

+2
source

Source: https://habr.com/ru/post/1584316/


All Articles