我有一個使用Angular的對象,而categoryOne
的內容會自動加載到我的頁面上。如果點擊一個按鈕,我想在控制器中調用一個函數 - 這將是對象下面的loadContent
函數 - 從頁面中刪除categoryOne
的內容,並在其位置注入categoryTwo
的內容。如何將動態變量連接到對象路徑
在我的loadContent
函數中,我想針對每個對象categoryTwo
的content
對象。換句話說,$scope.layout.categories.categoryTwo.content.contentX.text
其中「X」可以是1或2
的事情是,我無法找到有關的「路徑」,即在一個對象瞄準的東西串聯動態變量在網絡上任何東西。在上面的段落中,「X」是動態變量,我所指的這個「路徑」是我試圖從我的對象對象中抓取的東西,如果這樣做是有道理的。
tl; dr如何將動態變量連接到試圖從對象對象中獲取東西的路徑上?
非常感謝你幫助我。虛擬高五爲你們所有人。
var app = angular.module("app1", []).controller("appCtrl", ["$scope", "$http", function($scope, $http)
{
$scope.layout =
{
"name": "test_proj",
"title": "Test Project",
"categories":
{
"categoryOne":
{
"heading": "Category 1",
"links":
{
"link1": "www.domain.com"
},
"content":
{
"content1":
{
"text": "This is some text.",
"help": "Help text 1."
},
"content2":
{
"text": "Apples.",
"help": "Help text 2."
}
}
},
"categoryTwo":
{
"heading": "Category 2",
"links":
{
"link1": "www.generic.com"
},
"content":
{
"content1":
{
"text": "More text here.",
"help": "Help text 1."
},
"content2":
{
"text": "Oranges.",
"help": "Help text 2."
}
}
}
}
}
$scope.loadContent = function()
{
var catLength = 0;
for (var key in $scope.layout.categories.categoryTwo.content)
{
if ($scope.layout.categories.categoryTwo.content.hasOwnProperty(key))
{
++catLength;
}
}
$(".cool-container").html("");
for (var x = 0; x < catLength; x++)
{
$(".cool-container").append("<p class='content'>" + $scope.layout.categories.categoryTwo.content.contentX.text + "</p>");
// Where it says "contentX" in the line above, I want "X" to be a dynamic variable that will make it "content1" and "content2"
}
}
}]);
[動態地訪問對象的屬性使用可變](的可能的複製http://stackoverflow.com/questions/4244896/dynamically-access- object-property-using-variable) –