rascio rascio - 1 year ago 66
AngularJS Question

Angularjs click and display from a list

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 = [];

<body ng:controller="MyController">
<p>selected: <span ng:bind="selected" ng:init="selected='none'" /></p>
<li ng:repeat="artist in list">
<button ng:click="selected = artist.name" >{{artist.name}}</button>
<li ng:repeat="song in songs">

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

Answer Source

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>
    <li ng:repeat="artist in list">
      <button ng:click="select(artist)" >{{artist.name}}</button>

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download