当ng-options列表被改变时,Ng-init不工作

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

本文关键字:Ng-init 工作 改变 ng-options 列表      更新时间:2023-09-26

下面的select元素加载并选择控件加载时的第一个选项。我基于另一个下拉列表改变了positionAllowedList。但是ng-init不选择第一项。

<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文档本身说:

ngInit唯一合适的用法是混叠ngRepeat的特殊属性,如下面的演示所示。除了这种情况,你应该使用控制器而不是ngInit来初始化作用域中的值。

所以一般用法是用ng-repeat来混叠它的特殊属性,如$index, $first等,例如,当你在子ng-repeat中使用嵌套的ng-repeat时,你可以通过ng-init设置的别名访问父ng-repeat的$index,而不使用$parent.$index, $parent.$parent...$index等。

它也只是一次初始化,如果你看一下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