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

时间:2015-06-01 17:07:42

标签: javascript html angularjs initialization

下面的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;

                })

            }

1 个答案:

答案 0 :(得分:2)

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

  

ngInit的唯一合适用途是用于别名ngRepeat的特殊属性,如下面的演示所示。除了这种情况,您应该使用控制器而不是ngInit来初始化作用域上的值。

因此通常使用ng-repeat来对其特殊属性(如$index$first等设置别名,例如,当您在子ng-repeat中使用嵌套ng-repeat时,您可以访问父级ng-repeat的$index通过ng-init设置的别名而不使用$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,以便在每个摘要周期中重新评估表达式。所以不出所料,它无法正常工作。

所以只需从ng-init移除select,然后在控制器本身内设置属性col.positionselected

相关问题