ngSelected 不会更新 ngModel [AngularJS]



下面我有以下选择列表。ngSelected 确实正确选择了表达式中的值,但选择的模型不会相应地更新。我可以选择"高"值,当 ngSelected 触发时,将显示空值,但模型保持为"高"。

有人知道如何在触发ngSelected后以编程方式设置ngModel吗?ngSelected 中的表达式来自div 上的指令,所以我无法在其上附加 ngChange。

<select class="form-control" name="alertLevel-{{$index}}" ng-model="template.service.readings[$index].repeatBreachAlert.repetitiveAlertLevel" title="Please select an alert level">
      <option ng-selected="template.service.firstLevelMessage.below.messages | messagesLength.length === 0" value=""></option>
      <option value="Valid">Valid</option>
      <option value="High">High Alert</option>
      <option value="Low">Low Alert</option>
</select>

这是从angular官方网站上取的。

注意:ngSelected 不与 select 和 ngModel 交互 指令,它只设置元素上的选定属性。如果你 在选择上使用 ngModel,您不应该在 选项,因为 ngModel 将设置选择值和所选选项。

话虽如此。您应该在控制器中初始化模型并删除 ng 选择的指令。

这样的东西会起作用:

function initializeModel() {
  for (let i; i < whatEverMyIterationLooksFor; i++) { // I suppose you are using ng-repeat in template so here you should iterate through the relevant scope.
    const shouldBeEmpty = template.service.firstLevelMessage.below.messages || messagesLength.length === 0; // You also had a typo here with the OR operator.
    if (shouldBeEmpty) {
      template.service.readings[i].repeatBreachAlert.repetitiveAlertLevel = null;
    };
  }
}

使用它在视图中设置模型,以解决此答案:

<span class="ng-hide">
   {{((template.service.firstLevelMessage.above.messages | messagesLength).length === 0  && template.service.readings[$index].repeatBreachAlert.repetitiveAlertLevel !== 'Valid' ? template.service.readings[$index].repeatBreachAlert.repetitiveAlertLevel = '' : '' }}
</span>

最新更新