为什么AngularJS控制器中的另一个变量会发生变化?

时间:2015-11-11 18:31:57

标签: javascript json angularjs getjson javascript-objects

我有一个如下的AngularJS控制器:

schedule.controller('schedule', ['$scope', '$http', function($scope, $http){
    $http.get('/zt-api/business/admin/' + window.location.pathname.split('/')[2]).success(function(data){
        $scope.admin_times = data;
        $scope.admin_times_unix = data;
        $scope.weekDays = {'Saturday': "شنبه", 'Sunday': "یکشنبه", 'Monday': "دوشنبه", 'Tuesday': "سه شنبه",
            'Wednesday': "چهارشنبه", 'Thursday': "پنجشنبه", 'Friday': "جمعه"};
        angular.forEach($scope.admin_times, function (value, key) {
            angular.forEach(value, function (value2, key2) {
                angular.forEach(value2, function (value3, key3) {
                    angular.forEach(value3, function (value4, key4) {
                        angular.forEach(value4, function (value5, key5) {
                            var info = $scope.admin_times[key]["week_"+ key][key3].times[key5];
                            if (!isNaN(info)){
                                var myObj = $.parseJSON('{"date_created":"'+ $scope.admin_times[key]["week_"+ key][key3].times[key5] +'"}'),
                                myDate = new Date(1000*myObj.date_created);
                                $scope.admin_times[key]["week_"+ key][key3].times[key5] = myDate.toLocaleString().split(", ")[1]
                            }
                        });
                    });
                });
            });
        });
    });
}]);

我更改$scope.admin_times,但我不知道为什么$scope.admin_times_unix也会发生变化! 你能救我吗?

1 个答案:

答案 0 :(得分:5)

因为您要将data的相同引用分配给admin_times以及admin_times_unix对象。

这就是改变一个对象的原因,影响其他对象。

您可以使用angular.copy来解决此问题,$scope.admin_times_unix = angular.copy(data); 会创建新的引用,而不是分配其实际引用。

var check_frequency = 30000;
Meteor.setInterval((function() {
    // figure out what elements will expire within the next check period
    var next_check = moment().add(check_frequency, 'milliseconds');
    var next_string = next_check._d.toISOString();

    var ending_items = items.find({'time_to_end': {$lt : next_string}});

    ending_items.forEach(function(db_object) {
        var time_from_now = moment(db_object.time_to_end) - moment();
        Meteor.setTimeout(function() {
            removeAndReport(db_object._id);
        }, time_from_now);

    });
}), check_frequency);