2013-09-30 224 views
1

我想創建使用AngularJS日曆,我的模型是這樣的對象:創建JavaScript對象動態

$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"}]}]); 
      } 
     } 
    } 

誰能幫助我?提前致謝!

回答

6

問題是weeks不存在。您需要先創建它像這樣:

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

之後,你不想推空數組,而不是推一個包含天數組的新對象:

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

然後,您可以推你的日子重視像這樣,對空:

weeksObj.days.push(null); 

,併爲您的天對象,再創建一個新的對象:

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

希望這會幫助你看到你的問題在哪裏。看起來你在一個對象({})和一個數組([])之間混了一點。只有陣列具有推式方法

1

在您的循環中,不要推入空數組,而是將周設置爲空數組。並且不要忘記創建第一天的對象

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"}]}]); 
     } 
    } 
+0

周必須設置。 (我只是編輯我的答案) – peernohell