Angularjs从列表中单击并显示

时间:2012-02-22 16:51:39

标签: javascript angularjs angularjs-controller

我想创建一个简单的列表,当用户点击某个按钮时,该值会显示在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>

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

1 个答案:

答案 0 :(得分: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/