Pergunta

Quero criar uma lista simples e quando o usuário clicar em um botão, o valor será exibido em um elemento span.

HTML e controlador

<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>

Desejo exibir dinamicamente a lista de músicas do artista clicado.Essa é a abordagem certa?

Foi útil?

Solução

O problema é que ng:repeat cria um novo escopo, então você está definindo selected no escopo atual, mas o span está vinculado a um escopo pai.

Existem várias soluções, definindo um método provavelmente o melhor:

<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>​

E o controlador:

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"]
  }];
}​

Aqui está seu exemplo de trabalho em jsfiddle: http://jsfiddle.net/vojtajina/ugnkH/2/

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top