Angularjs click and display from a list
-
29-10-2019 - |
문제
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?
해결책
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/
제휴하지 않습니다 StackOverflow