1

我想使用创建日历AngularJS,我的模型是这样的对象:

$scope.model = {
        weeks: [
                {
                    days: [
                    null,
                    {
                        name: "3 dec",
                        toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]
                    },
                    {
                        name: "4 dec",
                        toDoItems: [{name: "Task 1"}, {name: "Task 2"}]
                    }
                ]
                },
                {
                    days: [
                    null,
                    {
                        name: "5 dec",
                        toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]
                    },
                    {
                        name: "6 dec",
                        toDoItems: [{name: "Task 1"}, {name: "Task 2"}]
                    }
                ]
                }

            ]
           }

但我想动态创建对象。

我试过这样的事情,但它给了我以下错误:

TypeError: Cannot call method 'push' of undefined



 $scope.fillMonth = function () {
        var gap = dayInWeek($scope.year.value, $scope.month, 1),
            nrOfDays = daysInMonth($scope.year.value, $scope.month);

        $scope.model = {};

        for (var i = 0; i < (nrOfDays + gap) % 7; i++) {
            for (var j = 0; j < 7; j++) {
                if (j === 0)
                    $scope.model.weeks.push([]);

                if (i === 0 && j < gap)
                    $scope.model.weeks[i].days.push(null);

                else
                    $scope.model.weeks[i].days.push([{ name: i + ' ' + j, toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]}]);
            }
        }
    }

谁能帮我这个?提前致谢!

4

2 回答 2

6

问题是weeks不存在。您需要先像这样创建它:

$scope.model = {};//new object
$scope.model.weeks = [];//new array

之后,您不想推送一个空数组,而是推送一个包含 days 数组的新对象:

var weeksObj = {};//new object
weeksObj.days = [];//new array
$scope.model.weeks.push(weeksObj);

然后,您可以像这样推送您的天值,为 null:

weeksObj.days.push(null);

对于您的 days 对象,再次创建一个新对象:

var dayObj = {};//new object
dayObj.name = "name";//set name property
dayObj.toDoItems = [];//new array
weeksObj.days.push(dayObj);

希望这将帮助您了解问题所在。{}似乎您在对象 ( ) 和数组 ( )之间有点混淆了[]。只有数组有 push 方法

于 2013-09-30T15:46:26.250 回答
1

在您的循环中,不要推送一个空数组,而是将周数设置为一个空数组。并且不要忘记用 day 创建第一个对象

    for (var i = 0; i < (nrOfDays + gap) % 7; i++) {
        for (var j = 0; j < 7; j++) {
            if (j === 0)
                $scope.model.weeks = [];

            if (i === 0 && j < gap)
                $scope.model.weeks[i] = {day: [null]};

            else
                $scope.model.weeks[i].days.push([{ name: i + ' ' + j, toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]}]);
        }
    }
于 2013-09-30T15:49:04.270 回答