2015-06-11 21 views
0

Javascript object creation on the fly如何使用變量隨時使用AngularJS創建對象?

create objects on the fly with angularjs

好了,所以,是的,我可以動態創建對象。但是我很難將其實現到我自己的代碼中。這裏是我有:

var holdBuilding = $scope.m1Special.Buildings; 
var c = 0; 
$scope.m2Info = {}; 

angular.forEach(holdBuilding,function(){ 
    if($scope.m1Special.Buildings[c].loc=="Northern"){ 
     alert(holdBuilding[c].name); 
     $scope.m2Info=[{ 
      name:holdBuilding[c].name; 
      link:holdBuilding[c].link; 
     }]; 
     c++; 
    }; 
}); 

我的代碼似乎像第一個鏈接超過第二,但第二個使用Angular。儘管如此,我認爲他正在做一些與我不同的事情。或者,也許我正在接近這個錯誤。

當我運行代碼時,Angular完全打破了。如果我註釋掉不過本節,:

$scope.m2Info=[{ 
     name:holdBuilding[c].name; 
     link:holdBuilding[c].link; 
    }]; 

然後代碼運行,我能夠看到該警示不正確地提醒。它只是不喜歡對象構建部分。我究竟做錯了什麼?

,我得到當角斷裂是錯誤:

SyntaxError: missing } after property list

線路:

name:holdBuilding[c].name; 
+0

定義「完全中斷」。 –

+0

當Angular完全斷開時,它會顯示頁面上的所有插值。任何來自Angular控制器的內容都不會顯示。 – Christine268

+0

而在控制檯中的錯誤是? –

回答

1

Alt鍵的關鍵。 1:

$scope.m2Info.name = holdBuilding[c].name; 
$scope.m2Info.link = holdBuilding[c].link; 

您已擁有一個對象,您只需設置屬性即可。

Alt。 2:

$scope.m2Info = { 
        name: holdBuilding[c].name, 
        link: holdBuilding[c].link 
       }; 

要定義包括您按照語法name: value,屬性的新對象。最後一個屬性不需要逗號。

+0

把你的問題標爲答案,結果我只需要用* comas *替換*分號*,呃,當我做出簡單的愚蠢的語法錯誤時討厭它。很高興知道我以其他方式做對了! – Christine268

0

您應該使用angular.copy如果您要更換整個數組或對象。這將更新對原始對象的引用。

此外,您不需要手動跟蹤迭代器。 angular.forEach函數包含作爲第一個參數的對象。

var buildings = $scope.m1Special.Buildings; 
$scope.m2Info = []; 

angular.forEach(buildings, function(building) { 
    if (building.loc=="Northern") { 
     alert(building.name); 
     angular.copy([{ 
      name:building.name; 
      link:building.link; 
     }], $scope.m2Info); 
    }; 
}); 

應當指出的是$scope.m2Info將永遠只包含建築數組中的最後一個對象。您可能需要改用$scope.m2Info.push(building);

編輯:你也可以通過第二個參數在foreach功能angular.forEach(buildings, function(building, key) {...}

+0

我想複製它是好的,永遠不會有任何時間,任何對象*改變*在飛行中。但是,如何讓'$ scope.m2Info'只包含buildings數組中的最後一個對象?做'angular.forEach'的要點是捕獲**所有**建築物陣列中的物體。基本上是我試圖複製它,而不復制和粘貼它,因爲我在其他地方使用它...但不能使用原來的.. – Christine268

+1

然後你想要使用'$ scope.m2Info.push({name :building.name,link:building.link});'而不是angular.copy。在使用'$ scope.m2Info = ...'明確覆蓋之前的'$ scope.m2Info'之前(除非該行應該是'$ scope.m2Info [c] = ...')。 – csbarnes

+0

哦,好吧,我現在明白了。是的,使用當前代碼,如果我執行了alert($ scope.m2Info [0] .name),它會提醒位於原始對象中的每個名稱;'所以它正如你所說的覆蓋它。將其更改爲$ scope.m2Info [c] = ...'謝謝! – Christine268