更改 ng-options 列表时 ng-init 不工作

ng-init not working when the ng-options list is changed

下面的 select 元素加载并且 select 是控件加载的第一个选项。 我根据另一个下拉列表更改了 positionAllowedList。 但是 ng-init 没有 select 第一项。

<select ng-init="col.positionselected = col.positionAllowedList[0].value" ng-options="pos.value as pos.text for pos in col.positionAllowedList" ng-model="col.positionselected">
                                                </select>

$scope.ChangeBookingIso = function (col) {
                $.each(col.bookingIsoList, function (i, item) {                   
                        ....someLogic to change it is exactly the same structure the json list as before at the first time loaded.....
                        col.positionAllowedList = positionAllowedList;

                })

            }

您使用了错误的指令。 ng-init 从未设计为基于视图上的任意(尽管可能被滥用)表达式进行初始化。 ng-init 文档本身说:

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

所以一般用法是使用 ng-repeat 为其特殊属性设置别名,例如 $index$first 等,例如当您在子 ng-repeat 中使用嵌套的 ng-repeat 时可以通过 ng-init 设置的别名访问父 ng-repeat 的 $index 而无需使用 $parent.$index$parent.$parent...$index

也是一次性初始化,看一下source for ng-init就很简单直接了。

var ngInitDirective = ngDirective({
  priority: 450,
  compile: function() {
    return {
      pre: function(scope, element, attrs) {
        scope.$eval(attrs.ngInit);
      }
    };
  }
});

如果您注意到没有创建 watch 以便在每个摘要循环中重新评估表达式。 所以不出所料,它没有按照您的预期工作上班。

因此,只需从 select 中删除 ng-init,然后在控制器本身中设置 属性 col.positionselected