Angularjs selectbox 在使用 ng-bind-html 时不反映底层 ng-model
Angularjs selectbox not reflecting underlying ng-model when using ng-bind-html
乍
一看,这看起来像是异国情调的东西,但这样做的主要目的是用选项组和颜色很好地风格化选择框。
下面是标记的简化示例:
<select ng-model="query.Statuses" multiple="" ng-bind-html="to_trusted(opts)">
</select>
和控制器:
app.controller('MainCtrl', function($scope, $sce) {
$scope.to_trusted = function(html_code) { return $sce.trustAsHtml(html_code); };
$scope.opts = '<option value="Draft">Draft</option>'+
'<option value="Pending">Pending</option>'+
'<option value="Live">Live</option>'+
'<option value="Deleted">Deleted</option>';
$scope.query = {
Statuses: ["Pending","Live"]
};
});
这是 plunker:http://plnkr.co/edit/Kv5xkl1KQVxgwGfnVpeZ?p=preview
如您所见,未选择所需的两个选项。
为什么不在 ng-repeat 中运行您的选项?
$scope.opts = ['Draft', 'Live']; // etc
然后在您的 HTML 中
<option value="opt" ng-repeat="opt in opts">{{opt}}</option>
不要使用 ng-model,而是设置一个模糊或更改事件,以触发函数以根据需要操作示波器数组
在控制器中设置 HTML 代码不是一个好的做法。您必须将视图代码和控制器代码分开。尝试使用 ng-repeat 在视图中包含一个模板选项标签,并使用 javascript 对象或关联数组在控制器中设置选项。
您还可以在选择标记中使用 ng-options,如下所述:https://docs.angularjs.org/api/ng/directive/select
与其使用ng-bind-html
或ng-repeat
为什么不坚持使用select
的ng-option
指令来做AngularJS呢?
分叉演示
.HTML
<select ng-model="query.Statuses" multiple
ng-options="status for status in statuses"></select>
JAVASCRIPT
app.controller('MainCtrl', function($scope) {
$scope.statuses = ['Draft', 'Pending', 'Live', 'Archived', 'Deleted'];
$scope.query = { Statuses: ["Pending","Live"] };
});
或者,如果您希望有一个复杂的选项集,其中您需要一些样式或禁用选项,那么您可以同时使用 ng-repeat
和 ng-selected
。
演示
.HTML
<select ng-model="query.Statuses" multiple>
<option ng-repeat="status in statuses" value="{{status}}" ng-bind="status"
ng-selected="query.Statuses.indexOf(status) >= 0"></option>
</select>
相关文章:
- 从 Javascript 中设置 ng-model name
- Toggle Switch在包含ng model和ng repeat之后不进行切换
- 在Angularjs中,我如何使用ng repeat、ng model和ng click来动态更改内容
- 当与之关联的 ng-model 为 false 时,Angularjs 复选框值不会取消选中
- ng-model 绑定到选择标签生成的空默认值
- 对象不能在angularjs ng-model中访问
- 为什么 HTML 中的 Value 属性在与 AngularJS 中的 ng-model 一起使用时不起作用
- ng-repeat不绑定ng-model对象数组
- AngularJS:ng-model 绑定在使用 jQuery 更改时不会更新
- 选择/选项 ng-model 未绑定 ng-selected
- Angular ng-model 将数据作为数组发送到 rails-api
- 为什么 AngularJS 在使用 ng-model 时不会在文本框上设置长度属性
- AngularJS:Ng:init-如何分配Ng:model
- 在指令中使用 ng-model 和 ng-repeat
- 使用 angularjs 访问控制器中的 ng-model 数据
- 如何在 Angularjs 中为 ng-model 增加价值
- 如何在 AngularJS 中将 ng-model 值检索到控制器
- 从角度“ng-model”选择元素中选择第一个选项,带有一个按钮
- 使用 ID 更新文本区域值,而不是在 AngularJs 中使用 ng-model
- Angularjs selectbox 在使用 ng-bind-html 时不反映底层 ng-model