最近工作遇到了這麼一個問題,嵌套了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上的值的時候,需要往父作用域跳兩層,才能綁定到控制器對應的變量上。
不過這樣感覺很不優雅,如果頁面結構改變了,對應的父作用域也會變,還需要修改代碼程序才能正確執行。
不知道大家有沒有其他好的方法?