AngularJS forEach .push undefined

时间:2014-03-11 05:33:37

标签: angularjs

我是AngularJS的新手(本周开始),我想从$ http.post返回的数据中提取几个项目,并创建一个带有数据子集的新对象$ scope.tests.latLngAll。

如果我在forEach中使用.push执行以下操作,我会收到一个错误,即$ scope.tests.latLngAll未定义,即使我尝试在第4行定义它。

$scope.tester = function( ){    

$scope.tests = {};
$scope.tests.latLngAll = {};

$http.post( '/src/shops.php' , $scope.postdata )
    .success( function(data) {

    $scope.tests = data;

    angular.forEach( $scope.tests, function( value, key ){ 
        $scope.tests.latLngAll.push( { key :  value } ); 
        }); 
    })          
}

如果我用'='替换.push,数组中的最后一项是分配给$ scope.tests.latLngAll的唯一值,这是有道理的。

$ scope.tests.latLngAll =({key:value});

我认为这意味着数据存在并且可以通过forEach'value'访问,但我没有做正确的推动。

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

未定义的'latLngAll'问题是由数据引起的。您必须确保数据必须包含名为“latLngAll”的数组对象。如果要动态添加latLngAll,可以试试这个:

$scope.tester = function( ){    

  $scope.tests = {};
  //$scope.tests.latLngAll = {};

  $http.post( '/src/shops.php' , $scope.postdata )
    .success( function(data) {

    $scope.tests = data;

    var tempArr = [];
    angular.forEach($scope.tests, function(value,key){
     tempArr.push( { key :  value } );
    });
    $scope.tests.latlngAll=tempArr;
    console.log($scope.tests.latlngAll);
  });          
}

这是jsfiddle demo

答案 1 :(得分:1)

试试这个:

$scope.tests.latLngAll = {};

替换为:

$scope.tests.latLngAll = [];

答案 2 :(得分:0)

试试这个

$scope.tester = function( ){    

    $scope.tests = [];
    $scope.tests.latLngAll = [];

    $http.post( '/src/shops.php' , $scope.postdata )
        .success( function(data) {

        $scope.tests = data;

      angular.forEach($scope.tests, function(value, key){
           this.push(key + ': ' + value);
       }, $scope.tests.latLngAll);
        });       
    }