Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  118] [ 7]  / answers: 1 / hits: 25510  / 13 Years ago, wed, february 22, 2012, 12:00:00

I want to create a simple list and when the user clicks on a button the value is displayed in a span element.



HTML & Controller



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




I want to dynamically display the list of songs of the clicked artist. Is this the right approach?


More From » angularjs

 Answers
73

The problem is, that ng:repeat creates new scope, so you are setting selected in current scope, but the span is bound to a parent scope.



There are multiple solutions, defining a method probably the best:



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


And the controller:



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


Here is your example working on jsfiddle: http://jsfiddle.net/vojtajina/ugnkH/2/


[#87293] Tuesday, February 21, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darrylm

Total Points: 499
Total Questions: 131
Total Answers: 108

Location: Saudi Arabia
Member since Mon, Sep 5, 2022
2 Years ago
;