温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-06-28 04:12:03 来源:网络 阅读:2013 作者:罗兹威尔 栏目:开发技术

最近工作遇到了这么一个问题,嵌套了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上的值的时候,需要往父作用域跳两层,才能绑定到控制器对应的变量上。


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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI