6

我想创建一个简单的列表,当用户单击按钮时,值将显示在 span 元素中。

HTML & 控制器

<html xmlns:ng="http://angularjs.org">
<script src="http://code.angularjs.org/angular-0.9.19.js" ng:autobind></script>
<script type="text/javascript">
function MyController(){
    this.list = [{name:"Beatles", songs: ["Yellow Submarine", "Helter Skelter", "Lucy in the Sky with Diamonds"]}, {name:"Rolling Stones", songs:["Ruby Tuesday", "Satisfaction", "Jumpin' Jack Flash"] }]

    this.songs = [];

}
</script>
<body ng:controller="MyController">
<p>selected: <span ng:bind="selected" ng:init="selected='none'" /></p>
    <ul>
        <li ng:repeat="artist in list">
            <button ng:click="selected = artist.name" >{{artist.name}}</button>
        </li>
    </ul>
    <!--ol>
        <li ng:repeat="song in songs">
            {{song}}
        </li>
    </ol-->
</body>

我想动态显示点击艺术家的歌曲列表。这是正确的方法吗?

4

1 回答 1

16

问题是,这ng:repeat会创建新范围,因此您selected在当前范围内进行设置,但跨度绑定到父范围。

有多种解决方案,定义一种方法可能是最好的:

<div ng:controller="MyController">
<p>selected: {{selected.name}}</p>
  <ul>
    <li ng:repeat="artist in list">
      <button ng:click="select(artist)" >{{artist.name}}</button>
    </li>
  </ul>
</div>​

和控制器:

function MyController() {
  var scope = this;

  scope.select = function(artist) {
    scope.selected = artist;
  };

  scope.list = [{
    name: "Beatles",
    songs: ["Yellow Submarine", "Helter Skelter", "Lucy in the Sky with Diamonds"]
  }, {
    name: "Rolling Stones",
    songs: ["Ruby Tuesday", "Satisfaction", "Jumpin' Jack Flash"]
  }];
}​

这是您在 jsfiddle 上工作的示例:http: //jsfiddle.net/vojtajina/ugnkH/2/

于 2012-02-22T18:51:24.397 回答