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

标签 javascript html angularjs initialization

下面的选择元素加载并选择控件加载时的第一个选项。 我根据另一个下拉列表更改了 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 从未设计为基于 View 上的任意(尽管可能被滥用)表达式进行初始化。 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 并在 Controller 本身内设置属性 col.positionselected

关于javascript - 更改 ng-options 列表时 ng-init 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30579223/

相关文章:

php - 使用 jQuery .toggleClass 的可选图像或使用 php/css 作为复选框的图像,大多数用户可以使用哪种方法?

javascript - AngularJS + Typescript => Controller 范围

javascript - 在 Angular.js 中使用工厂和 Controller 之间的逻辑

html - 使用 tomcat 查看文件时,HTML 中的非英文字符出现乱码

javascript - 为什么 document.getElementById 在我的脚本中不起作用?

javascript - AngularJS REST 资源 - 刷新查询

javascript - 如何将单个 html 表单发送到 OneSignal 服务器和另一个服务器

javascript - 你能得到(如果可能的话使用 jQuery)元素的当前滚动位置吗?

javascript - jquery链淡入淡出方法不起作用

javascript - 使用javascript的字符串连接