mon*_*jbl 19 javascript model-view-controller angularjs
所以,我想用vanilla JS做的事情相当简单,但是我正在使用AngularJS,我想知道如何在框架内做到最好.我想在多选框中更新所选选项.我不想添加或删除任何选项.这是我的HTML的样子:
<select multiple>
<option value="1">Blue</option>
<option value="2">Green</option>
<option value="3">Yellow</option>
<option value="4">Red</option>
</select>
Run Code Online (Sandbox Code Playgroud)
使用以下数组,我想以编程方式从此列表中选择/取消选择选项:
[{id:1, name:"Blue"},{id:4, name:"Red"}]
Run Code Online (Sandbox Code Playgroud)
当我在范围内设置此数组时,我希望选择框取消选择非蓝色或红色的任何内容并选择蓝色和红色.我在Google网上论坛上看到的标准回复是使用ng-repeat.但是,我无法每次都重新创建列表,因为所选值列表不完整.据我所知,AngularJS没有这方面的机制,我不知道如何在不使用jQuery的情况下做到这一点.
Pix*_*its 28
ngModel非常棒!如果将索引指定为模型selectedValues
<select multiple ng-model="selectedValues">
Run Code Online (Sandbox Code Playgroud)
从你的list(selected)中构建的$watch
$scope.$watch('selected', function(nowSelected){
// reset to nothing, could use `splice` to preserve non-angular references
$scope.selectedValues = [];
if( ! nowSelected ){
// sometimes selected is null or undefined
return;
}
// here's the magic
angular.forEach(nowSelected, function(val){
$scope.selectedValues.push( val.id.toString() );
});
});
Run Code Online (Sandbox Code Playgroud)
ngModel会自动为您选择它们.
请注意,此数据绑定是单向的(selected对UI).如果您想使用<select>UI来构建列表,我建议重构数据(或使用其他数据,$watch但这些数据可能很昂贵).
是的,selectedValues需要包含字符串,而不是数字.(至少它对我有用:)
http://jsfiddle.net/JB3Un/上的完整示例
| 归档时间: |
|
| 查看次数: |
57069 次 |
| 最近记录: |