Angularjs click and display from the list

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

HTML and 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 a list of songs of a clicked artist. Is this the right approach?

+6
source share
1 answer

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

There are several solutions that define a method, possibly 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/

+15
source

Source: https://habr.com/ru/post/909102/


All Articles