Angularjs selectbox 在使用 ng-bind-html 时不反映底层 ng-model

Angularjs selectbox not reflecting underlying ng-model when using ng-bind-html

本文关键字:ng-model selectbox ng-bind-html Angularjs      更新时间:2023-09-26

一看,这看起来像是异国情调的东西,但这样做的主要目的是用选项组和颜色很好地风格化选择框。

下面是标记的简化示例:

<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-htmlng-repeat为什么不坚持使用selectng-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-repeatng-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>