Angularjs hacer clic y mostrar desde una lista
-
29-10-2019 - |
Pregunta
Quiero crear una lista simple y cuando el usuario hace clic en un botón, el valor se muestra en un elemento de intervalo.
HTML y 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>
Quiero mostrar dinámicamente la lista de canciones del artista seleccionado.¿Es este el enfoque correcto?
Solución
El problema es que ng:repeat
crea un nuevo alcance, por lo que está configurando selected
en el alcance actual, pero el intervalo está vinculado a un alcance principal.
Existen múltiples soluciones, definir un método probablemente sea el mejor:
<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>
Y el 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"]
}];
}
Aquí está su ejemplo de trabajo en jsfiddle: http://jsfiddle.net/vojtajina/ugnkH/2/
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow