storm_buster
storm_buster

Reputation: 7568

How to set the value for an ng-model within a ng-repeat?

I have a ng-repeat, which I put inside an select tag. I want to be able to modify the selected values on different selects. here is what I have : the html

<div ng-controller="Ctrl">
    <div ng-repeat="user in users">
        <select ng-model="nbModel" ng-options="numValue.Text for numValue in numValues" ng-change="chooseUser(nbModel, user.id)">
                        </select>
        &nbsp;&nbsp;{{user.name}}&nbsp;&nbsp;-&nbsp;{{user.age}} years
    </div>
</div>

the js

function Ctrl($scope) {
    $scope.numValues = [ {Id : '0',Text : '0'}, {Id : '1',Text : '1'}, {Id : '2',Text : '2' }];    
    $scope.users = [];

    $scope.users.push(new User(1, 'Luke', 23));
    $scope.users.push(new User(2, 'Maria', 26));
    $scope.users.push(new User(3, 'Mike', 45));

    angular.forEach($scope.users, function(equip) {
        //TODO to set the default values for each select
    });

    $scope.chooseUser= function(value, name) {
        //some traitement        
        //TODO to set a wanted value        
    };
};

function User(id, name, age) {
    this.id=id;
    this.firstnamename = name;
    this.age = age;
}

I could not figure out how to manually set the selected options. any help?

Upvotes: 3

Views: 3658

Answers (1)

Ben Lesh
Ben Lesh

Reputation: 108471

You're half way there... what you need to do is set ng-model to something on your user you want to change. Presuming you wanted to change the age of the user with the select, it would look like this:

<div ng-controller="Ctrl">
    <div ng-repeat="user in users">
        <select ng-model="user.age" ng-options="numValue.Text for numValue in numValues"></select>
        &nbsp;&nbsp;{{user.name}}&nbsp;&nbsp;-&nbsp;{{user.age}} years
    </div>
</div>

Upvotes: 3

Related Questions