Angular无法读取属性' push'未定义的

时间:2016-08-26 09:31:45

标签: javascript angularjs

我创建了一个简单的新闻自动收录器,它似乎在我的codepen示例中正常工作。看来我的集成问题 - 代码结构。目前我收到以下错误。

Cannot read property 'push' of undefined

这是我的控制器的代码片段。

"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);


 }]);

3 个答案:

答案 0 :(得分:2)

你永远不会初始化$ scope.news,只需在控制器的开头添加$scope.news = []

答案 1 :(得分:0)

在控制器开始时,声明$scope.news= []

在$ scope.news中添加值时,此变量未定义

答案 2 :(得分:0)

你可以尝试

// 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();
 };