Leth
Leth

Reputation: 1059

Push multiple input strings to scope array, when input value changes (AngularJS)

I am trying to add strings to an empty array i have defined in my scope.

$scope.playerNames = [];

The number of elements in the array can vary depending on what the user types in the player count input field.

Right now I have a $watch function which checks whether the user increments or decrements the player count and adds new input fields for names accordingly. For each of these input fields, i want to add a name to an array, when the user starts typing it. Value from the input field og the first player would be placed at index 0 and so on.

When the user decrements the player count, the player name (if any) should be removed from the array.

$scope.$watch('playerCount', function (newValue, oldValue) {
        if (newValue > 7) {
            alert("Can't have more than 7 players.");
            $scope.playerCount = oldValue;
        }
        else if (newValue > oldValue) { //if increment player count
            $("#playerNames").append("<input id='player" + newValue +"' type='text' class='form-control' placeholder='Enter name for player" + newValue + "'>");

        }
        else if (newValue < oldValue) { //i decrement player count
            console.log("Removing")
            $("#player" + oldValue).remove();
        }
    });

Here's an example of how the form looks with 3 players: https://i.sstatic.net/1XHqw.png

Am i thinking of this problem correctly? Is there a better way to do it? I'm not sure how I should go about binding my generated input forms to my array defined in the scope.

Upvotes: 1

Views: 1774

Answers (1)

Vivz
Vivz

Reputation: 6630

You don't have to use a $scope.$watch. You can do this by using ng-repeat over an array which has the same number of values as player count.

var app = angular.module('testApp', []);
app.controller('testCtrl', function($scope) {
 $scope.player={"count":0};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="testApp" ng-controller="testCtrl">
<input type="number" ng-model="player.count"/>
    <div>
            <div ng-repeat="player in  [].constructor(player.count) track by $index">
                <input id="player{{$index+1}}" type="text" class="form-control" placeholder="Enter name for player {{$index+1}}" ng-model="player.value" />
            </div>
      </div>      
</body>

Upvotes: 4

Related Questions