javascript Angular UI.Bootstrap 的单选按钮在使用 ng-repeat 时表现得很奇怪

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16443873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:41:50  来源:igfitidea点击:

Angular UI.Bootstrap's radio buttons act strange with ng-repeat

javascriptangularjsangular-ui-bootstrap

提问by Blackle Mori

I have a problem dynamically generating options for a radio model in angular's ui.bootstrap. I thought I could simply ng-repeat over an array, using it's contents for the btn-radio attribute like so:

我在 angular 的 ui.bootstrap 中为无线电模型动态生成选项时遇到问题。我以为我可以简单地对数组进行 ng-repeat,将它的内容用于 btn-radio 属性,如下所示:

//in the controller
$scope.radioModel =  undefined;
$scope.radioModelButtons = ["a", "b", "c"];

//in the html
<div class="btn-group" >
  <button ng-repeat="value in radioModelButtons"
    class="btn" type="button" ng-model="radioModel"
    btn-radio="'{{value}}'">
      {{value}}
  </button>
</div>

I'm using angular 1.1.4 and ui.bootstrap 0.3.0.

我正在使用 angular 1.1.4 和 ui.bootstrap 0.3.0。

Here is a jsfiddle of my efforts, as you can see, the radio buttons act independently and do not affect the radioModel variable.

这是我努力的 jsfiddle,如您所见,单选按钮独立运行,不会影响 radioModel 变量。

Thanks!

谢谢!

回答by pkozlowski.opensource

This is how you should write your markup:

这是您应该如何编写标记:

<button ng-repeat="value in radioModelButtons"
        class="btn" type="button" ng-model="radio.model"
        btn-radio="value">
          {{value}}
</button>

And the working jsFiddle: http://jsfiddle.net/yMLqz/2/

和工作 jsFiddle:http: //jsfiddle.net/yMLqz/2/

There were 2 problems in your approach:

你的方法有两个问题:

  • btn-radioshould be used with AngularJS expression, and not an interpolated value
  • ng-repeatis creating a new scope so you need to take this into account if you want to bind to a value defined on a parent scope
  • btn-radio应该与 AngularJS 表达式一起使用,而不是内插值
  • ng-repeat正在创建一个新范围,因此如果您想绑定到在父范围上定义的值,则需要考虑到这一点