JavaScript(Angular)ForEach循环更改未应用

时间:2016-08-19 17:47:18

标签: javascript angularjs

我有一个对象数组,其日期格式为MMMM Do YYYY格式。我需要将它转换为UNIX时间戳来排列它们,然后将它们转换回可读日期格式。

但是,这样做。似乎我在forEach回调中的更改未应用于$scope.lalala变量。

我的代码:

    function compare(a, b) {
  if (a.date < b.date)
    return -1;
  if (a.date > b.date)
    return 1;
  return 0;
}
$scope.lalala = arrayofincompleteorders;
$scope.lalala.forEach(function(hiVanilla, index) {
  hiVanilla.date = moment(hiVanilla.date, 'MMMM Do YYYY').format('x');
  if (index == $scope.lalala.length - 1) {
    $scope.lalala.sort(compare); timestamps as expected
    console.log($scope.lalala); //logs the date property with unix 
    callback();
  }
});
console.log($scope.lalala); //logs the date property with unix timestamps, why?

function callback() {
  $scope.lalala.forEach(function(order, index) {
    console.log(order.date); //unix timestamp
    $scope.lalala[index].date = moment(order.date, 'x').format('MMMM Do YYYY');
    console.log($scope.lalala[index].date); //formatted timestamp
  });
};

编辑:即使回调中的angular.forEach循环,我也有同样的问题:

function callback(){
    angular.forEach($scope.lalala, function(value, key) {
    console.log(value.date);
  value.date = moment(value.date, 'x').format('MMMM Do YYYY');
  console.log($scope.lalala[key].date);
});
  console.log("fire!");
  $scope.apply();
};

我得到了成功更改的日期,但之后它说$scope.apply()不是一个能够完成其余部分操作的函数。

EDIT2:

我摆脱了回调并将所有内容放在一个angular.forEach中,但它仍然不适用?

$scope.lalala = arrayofincompleteorders;
 angular.forEach($scope.lalala, function(hiVanilla, key) {
  hiVanilla.date = moment(hiVanilla.date, 'MMMM Do YYYY').format('x');
  if (key == $scope.lalala.length - 1) {
    $scope.lalala.sort(compare); //timestamps as expected
    console.log($scope.lalala); //logs the date property with unix 
    console.log(hiVanilla.date); //unix timestamp
    hiVanilla.date = moment(hiVanilla.date, 'x').format('MMMM Do YYYY');
    console.log($scope.lalala[key].date); //formatted timestamp
  }
});
console.log($scope.lalala); //logs the date property with unix timestamps, why?

1 个答案:

答案 0 :(得分:0)

看起来我使用angular.forEach的方式并非如此设计。

以下工作,基本上我只是通过将它推入一个空数组而不是试图改变我在其中循环的数组来分配它:

        $scope.lalala=[];
        var log = = arrayofincompleteorders;
        angular.forEach(log, function(value, key) {
        if(value.complete!="TRUE")
        {
        i++;
        value.date = moment(value.date, 'x').format('MMMM Do YYYY');
        this.push(value); //put the new value in $scope.lalala as specified below
        }
        }, $scope.lalala);