ngRepeat With ngModel in RadioBtn

相信大家开始接触ng-repeat时,很容易就明白了以下代码的作用:

1
2
%li(ng-repeat="item in items")
  %span 

那么,当ng-repeatng-model结合起来呢:

1
2
3
4
%li(ng-repeat="item in items")
  %input(type="radio" ng-model="select_item" value="")

%input(type="text" value="select_item")

从代码上看,多个RadioBtn分在同一组,然后显示选择项的值。但是,这在实际操作中是不行的。

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

ng-repeat会为每个实例产生自己的作用域。也就是说,ng-model="select_item"items不是同一作用层级的;而相似的,ng-model="select_item"value="select_item"是同一作用层级的。所以,value="select_item"并不能正常访问ng-model="select_item"中的变化值,需要将ng-model提升层级,

1
2
3
4
%li(ng-repeat="item in items")
  %input(type="radio" ng-model="$parent.select_item" name="item" value="")

%input(type="text" value="select_item")

Comments