ng-if ng-repeat下的ng-model赋值

2023-06-02,,

最近工作遇到了这么一个问题,嵌套了2层ng-repeat的页面结构,第二层select组件在赋值时控制器取不到对应的值:

页面片段:

li.list-group-item.space-list-item(ng-repeat="space in current.spaces")
    span
        | `space`.`name`
    h6
        span.label.label-info(ng-hide="showIndex===$index", ng-click="toggleShowSpaceQuota($index)") 配额设置
    form.new-space-quota-form(ng-if="showIndex===$index")
        select.form-control(name='quota_select', ng-model='$parent.$parent.selectedSpaceQuota', ng-required='', ng-init="$parent.$parent.selectedSpaceQuota='f'")
            option(value='f',selected) -- 选择配额 --
            option(ng-repeat="x in currentSpaceQuota", value='`x`.`metadata`.`guid`') `x`.`entity`.`name`
        button.btn.btn-sm.btn-success(ng-click="changeSpaceQuota(space)" ng-disabled="$parent.$parent.selectedSpaceQuota=='f'")
            i.glyphicon.glyphicon-ok
        button.btn.btn-sm.btn-danger(ng-click="hideSpaceQuota()")
            i.glyphicon.glyphicon-remove

js片段

        $scope.selectedSpaceQuota = {};

后来上网稍微查了一下:

ng-if 和ng-repeat都是动态的添加或删除DOM(基于这点,就不需要记住所有的能创建作用域的指令;还有directive, ng-controller),所以会创建新的作用域,和指令一样;

首先最外层有个ng-repeat,其次form组件上面有个ng-if,这两个指令都会创建新的作用域,所以ng-model在绑定$scope上的值的时候,需要往父作用域跳两层,才能绑定到控制器对应的变量上。

不过这样感觉很不优雅,如果页面结构改变了,对应的父作用域也会变,还需要修改代码程序才能正确执行。

不知道大家有没有其他好的方法?

《ng-if ng-repeat下的ng-model赋值.doc》

下载本文的Word格式文档,以方便收藏与打印。