2016-12-14 65 views
1

我有两个选择菜单,通过页面加载后获取的AJAX JSON数据填充。他们通过他们自己的模型链接,看起来像这样;的形式被提交给API基于字符串设置选项值AJAX值

<select name="category" 
     id="category" 
     ng-model="category" 
     ng-options="category as category.name for category in categories track by category.name"> 
    <option value=''>Select category</option> 
</select> 

<select name="product" 
     id="product" 
     ng-disabled="!category" 
     ng-model="product" 
     ng-options="product for product in category.products"> 
    <option value=''>Select product</option> 
</select> 

之后,它返回一个origin对象包括两个categoryproduct串如果使用它们。

我想我应该能够将$scope.category和/或$scope.product设置为返回的origin数据以预先选择选择菜单中的项目;

.success(function(data)) { 
... 
$scope.category = data.origin.category 
... 
} 

但是,这并不工作...

回答

1

您可以使用ng-init选择初始值

<select ng-init="initDefaultCategory(categories)" name="category" id="category" ng-model="category" ng-options="category as category.name for category in categories track by category.name"> 
    <option value=''>Select category</option> 
    </select> 

    <select ng-init="initDefaultProduct(category.products)" name="product" id="product" ng-disabled="!category" ng-model="product" ng-options="product for product in category.products"> 
    <option value=''>Select product</option> 
    </select> 

工作DEMO

EDITS

如果要选择默认值,你可以做这样的事情

控制器

$scope.initDefaultCategory = function(categories, value) { 
    if (categories.length > 0) 
     $scope.category = categories.filter(e => e.name == value)[0]; 
    } 

而且你可以在ng-init

<select ng-init="initDefaultCategory(categories,'All')" name="category" id="category" ng-model="category" ng-options="category as category.name for category in categories track by category.name"> 
    <option value=''>Select category</option> 
    </select> 

Edited Demo

+0

谢谢Nagaveer。也许我还不够清楚 - 这些类别由相同的AJAX调用填充,因此用于检查类别的init将失败,因为它们还不存在。此外,我不想设置一个默认值,但匹配一个基于字符串值的特定项目 – Alex

+0

@Alex我更新了我的答案。希望这可以帮助!! –

+0

我认为我们正在接近,但有几个问题。首先,ng-init不会工作,因为构建类别的数据集在通过AJAX进行pagte加载后也是必需的。所以我得到一个“无法读取属性”长度的空“错误。这是有道理的,因为在初始化时不会填充类别。另外,由于某些原因,我的IDE不喜欢“e => e.name”运算符?!再次感谢 – Alex

1
.success(function(data)) { 
    $scope.category = $scope.categories.filter(function(val,key){ 
     return data.origin.category['yourKey']==val['yourKey'] 
    })[0] 
} 
传递价值