我是Angular的新手,嘗試使用Product對象。 Product對象包含許多Sku對象。角度更新模型數據維護選擇列表中的選定選項
用戶可以使用我的應用程序來獲取產品,該產品返回Product對象,其中包含Sku對象。當返回的產品對象,它的設置等於這樣的$scope.product
變量:
var app = angular.module('app', []);
app.controller('AppController', ['$scope', '$http', function($scope, $http){
$scope.product;
//this will contain the selected sku model that's selected in the dropdown
$scope.selectedSku;
/*
* Get a product and all of it's data from the server
*/
$scope.getProduct = function(){
$http.post('get_product', {product_id: $scope.extProductId}).
success(function(product){
$scope.product = product;
}).
error(function(data){
console.log('something went wrong');
});
};
正如你可以看到,有一個名爲$scope.selectedSku
一個額外的變量。該變量保存當前在選擇列表中選擇的Sku對象。選擇列表如下:
<select class="form-control input-lg" ng-model="selectedSku" ng-options="sku.sku for sku in product.skus">
<option value=""> -- Select SKU -- </option>
</select>
與應用程序與用戶的交互過程中有一些點,我想重新從服務器獲取Product對象。當我這樣做時,我再次將結果設置爲$scope.product
,就像以前一樣。但是,當我這樣做時,選擇列表不再有選擇正確的選項。相反,它會回到顯示`「 - 選擇SKU - 」選項。
我假設這是因爲基礎數據正在被一個新的Product對象替換。當產品對象被重新獲取時,Angular有沒有辦法維持與selectedSku的連接?
或者,解決方案是跟蹤所選SKU的ID,然後在產品重新獲取後以編程方式重新選擇該SKU?
產品對象,其中包含SKU的對象,看起來是這樣的:
{
id: 1,
name: "Product Name",
skus: [
{
id: 1,
name: "Sku 1 Name",
},
{
id: 2,
name: "Sku 2 Name"
}
]
}
什麼是數據結構'sku'對象? – zsong 2014-09-18 21:36:37
我剛剛添加了這個問題的結尾。這有幫助嗎? – flyingL123 2014-09-19 00:48:39