首页 > 其他 > 详细

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

时间:2017-06-29 17:04:56      阅读:353      评论:0      收藏:0      [点我收藏+]

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

页面片段:

li.list-group-item.space-list-item(ng-repeat="space in current.spaces")
    span
        | {{space.name}}
    h5
        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赋值

原文:http://rozwel.blog.51cto.com/13020465/1943133

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!