NewBoy NewBoy - 3 months ago 23
AngularJS Question

Angular Cannot read property 'push' of undefined

I have created a simple news ticker which seems to work fine on my codepen example. It seems i having a problem with integration - code structure. As it stands I am receiving the following error.

Cannot read property 'push' of undefined


Here is my a code snippet of my controller.

"use strict";

var app = angular.module('portlandApp');

// WEB SERVICE GET REQUEST
var NewsService = function ($http){
this.$http = $http;
}

NewsService.prototype.getarticles = function () {
return this.$http.get('app/data/news.json').then(function (response){
return response.data;
});
};

app.service("newsService", NewsService);

angular
.module('portlandApp')
.controller('newsCtrl', ['$scope', 'newsService', '$location', '$interval', '$timeout', function($scope, newsService, $location, $timeout, $interval) {

var promise = newsService.getarticles();
promise.then(function (data){
$scope.articles = data.news.map(function(item) {
//item.date = moment().format('Do MMMM YYYY');
return item;
});
console.log(data)
});
// AMOUNT OF ARTICLES
$scope.articleLimit = 4;

// NEWS TICKER FUNCTION
$scope.moving = false;

$scope.moveLeft = function() {
$scope.moving = true;
$timeout($scope.switchFirst, 1000);
};
$scope.switchFirst = function () {
$scope.news.push($scope.newsLink.shift());
$scope.moving = false;
$scope.$apply();
};

$interval($scope.moveLeft, 2000);


}]);

Answer

You can try

// NEWS TICKER FUNCTION
$scope.moving = false;


$scope.news = []  // need to define array before push value.

enter code here

$scope.moveLeft = function() {
   $scope.moving = true;
   $timeout($scope.switchFirst, 1000);
 };
$scope.switchFirst = function () {
   $scope.news.push($scope.newsLink.shift());
   $scope.moving = false;
   $scope.$apply();
 };
Comments