Kod*_*ode 3 javascript angularjs
我有一个多选下拉列表,在设置值时可以正常工作,但是一旦设置,我需要显示在更新表单中选择的内容.我的值存储在可通过REST访问的DB(SharePoint)中.这是一个示例REST输出,其中包含多个我的数组ID:
"CatId": [
18,
80,
84
],
Run Code Online (Sandbox Code Playgroud)
这是我的select函数,包括从REST中检索变量:
var currentCatValue = results.CatId;
$scope.categoryValues = [];
appCatList.query(function (categorydata) {
var categoryValues = categorydata.value; // Data is within an object of "value", so this pushes the server side array into the $scope array
// Foreach type, push values into types array
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
$scope.categoryValues.push({
label: categoryvalue.Title,
value: categoryvalue.ID,
});
})
var currentDetailIndex = $scope.categoryValues.map(function (e) { return e.value; }).indexOf(currentCatValue);
$scope.vm.selectedCategory = $scope.categoryValues[currentDetailIndex];
});
Run Code Online (Sandbox Code Playgroud)
这是我的HTML:
<select class="form-control" id="Event_Cat" data-ng-model="vm.selectedCategory"
data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
<option style="display:none" value="">Select a Category</option>
</select>
Run Code Online (Sandbox Code Playgroud)
编辑:在ng-model中使用id(灵感来自yvesmancera)将大大降低复杂性 - 您不需要预先处理您的选项和输入数组,只需将其插入并完成即可!
<select multiple ng-model="currentCatValue" ng-options="opt.ID as opt.Title for opt in categoryValues">
$scope.currentCatValue = currentCatValue;
$scope.categoryValues = categoryValues;
Run Code Online (Sandbox Code Playgroud)
注意:如果原始数据是对象,通常我们会将ng-options预先填充到数组中以保留选项的顺序.但是,由于您使用orderBy,因此可以将对象直接用作ng-options.
已过期:
您需要在ng-options中指向相同的对象,以便在加载时选择它们.
$scope.categoryValues = [];
$scope.vm.selectedCategory = [];
angular.forEach(categoryValues, function (categoryvalue, categorykey) {
var category = {
label: categoryvalue.Title,
value: categoryvalue.ID,
}
$scope.categoryValues.push(category);
if (currentCatValue.indexOf(parseInt(category.value)) != -1) {
$scope.vm.selectedCategory.push(category);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12822 次 |
| 最近记录: |