User183849481
User183849481

Reputation: 211

Set value of unknown number of inputs in AngularJS

I have a webapp dedicated to TV Shows. A controller fetches the registered TV Shows:

$http.get('/shows').success(function(data) {

    $scope.shows = data; 

    var temp = data[0];

    $scope.radio-input-shows = temp['name'];

});

This is passed to an AngularJS view, which displays them with a radio button.

<div class="col-use-list sidebar">

    <div class="col-md-12 sidebar-element sidebar-triangle" ng-repeat="show in shows" style="margin-bottom: 10px;">

        <div class="col-use-icon" style="padding-left: 0px;">

            <img alt="{{ show.name }}" src="img/artwork/{{ show.image_name }}.png" style="width:60px;height:60px;">

        </div>

        <div class="col-use-name">

            <p>{{ show.name }}</p>

        </div>

        <div class="col-use-select">

            <input type="radio" name="sidebar-radio" ng-model="radio-input-shows" value="{{ show.image_name }}">

        </div>

    </div>

    <tt>Show = {{radio-input-shows | json}}</tt><br/>

</div>

What I need now is to pass the name of a show as a value to the radio input. Is this even possible?

=================

So I now changed the input to this <input type="radio" name="checkbox" ng-model="tvshow" ng-value="show.name">. And changed this <tt>Show = {{tvshow}}</tt><br/>. However, it's still not updating if I click on another radio button... `

Upvotes: 0

Views: 228

Answers (1)

m59
m59

Reputation: 43785

Of course! You simply use ng-value to set the value according to an Angular expression, and use a $scope property.

<input type="radio" ng-model="whatever" ng-value="show.name">

Live Demo

You're also using invalid property names. radio-input-shows is not valid JavaScript and is throwing an error. That should camelCased radioInputShows or at least something that isn't a syntax error.

Lastly, you should always follow the "dot" rule so that child scope changes affect parent scopes.

<input type="radio" ng-model="foo.radioInputShows" ng-value="show.image_name">
<tt>Show = {{foo.radioInputShows | json}}</tt><br/>

In the controller:

$scope.foo = {
  // default value
  radioInputShows: '123'
};

This is just taking advantage of object references to share changes.

Upvotes: 1

Related Questions