2015-07-21 71 views
0

第一次嘗試獲取json數據並使用AngularJS將其綁定到我的表單。我能夠以這種方式綁定json,但它需要我手動將「data」匹配到我的html中的每個項目。從我的控制器AngularJS http get json

HTTP調用:

$http.get('static.json'). 
    success(function(data, status, headers, config) { 
     // here I have to manually copy all my json to bind with "data" 
     $scope.SiteID = data.SiteID; 
     $scope.SiteCode = data.SiteCode; 
    }). 
    error(function(data, status, headers, config) { 
    // log error 
    }); 

我的JSON:

{ 
    "SiteID":"mySiteIDGoesHere", 
    "SiteCode":"mySiteCodeGoesHere" 
} 

是否有我的JSON自動綁定,無需手動完成每個項目的方法嗎?例如:

$http.get('static.json'). 
    success(function(data, status, headers, config) { 
     "just pull in whatever my json is and bind it" 
     $scope.WhateverIsInJSONID = data.WhateverIsInJSONID; 
     $scope.WhateverIsInJSONCode = data.WhateverIsInJSONCode; 
    }). 
    error(function(data, status, headers, config) { 
    // log error 
    }); 
+0

只需設置'$ scope.something = data',然後你的視圖就會像:'{{something.WhateverIsInJSONID}}',或者其他任何 – Tom

回答

1

在你的成功的功能,綁定您的數據$範圍。數據像這樣:

$scope.data = data 

然後 - 你的HTML中,所有NG-模型,NG-值等將被綁定爲這樣:

<p>{{data.someKey}}</p><img ng-src="data.imgSrc" />.... 

此外,它的不安全以任意方式綁定許多鍵的範圍。我並不是指偶爾的數據或任何被添加到範圍內的東西。但是,當你盲目迭代一個對象並將每個鍵設置到$ scope時,可能會覆蓋其他可能已設置的鍵或稍後在控制器中覆蓋您的設置的鍵。也許你有一個函數附加到被盲分配覆蓋的範圍,反之亦然。

+0

Eureka那樣工作。 – simple

+0

給我一些luv並檢查它是否正確? – Brant

1

你可以只設置$scope.data = data; ...

然後在您的視圖中,您可以訪問data.SiteID,或data.SiteCode

1

如前所述,你可以簡單地設置在$scopedata一個項目,然後引用它使用點符號,如:

$scope.data = data; 

然後:

<span>{{data.WhateverIsInJSONID}}</span> 

如果你想每個屬性在$scope單獨,你將不得不遍歷他們,並添加它們,如:

for (var property in data) { 
    if (data.hasOwnProperty(property)) { 
    $scope[property] = data[property]; 
    } 
} 

這將使你$scope.WhateverIsInJSONID$scope.WhateverIsInJSONCode

+0

for循環示例的缺點是可能會覆蓋附加到範圍的以前的鍵。例如$ scope.someKey = function ...然後在返回的數據對象中有.someKey,然後覆蓋你的函數。不安全。 – Brant

+0

@Brant,同意,我不會這樣做,但要滿足我添加它的問題。 – Tom

+0

想你是因爲這個原因而添加的。 – Brant

-2

號在角你有一個內部的控制器將數據範圍($範圍)之一,那麼您可以在HTML或者{{等等}}或使用訪問ng-models指令,ng值等等。

+0

並非如此。 – Brant