hkguile
hkguile

Reputation: 4359

angularjs how to assign a value to a dynamic textfield

here is the html, the form will be displayed when user clicked "edit"

<div ng-repeat="item in items">
    <input type="text" placeholder="{{item.questionPlaceholder}}" ng-model="form.g1tags[item.tags_index]" required>
    <input ng-class="{'blockInput': !item.inlineChecked}" type="text" placeholder="enter text..." ng-model="form.g1tags_desc[item.tags_index]"  required>
   <input type="hidden" name="Group1" value="1">
</div>                         
<button class="addfields" ng-click="addG1Choice()">Add fields</button>

the full function in my angular controller

  $scope.edit = function(id){
    dataFactory.httpRequest('items/'+id+'/edit').then(function(data) {
        //console.log(data);
        $scope.form = data;


        for(var key in data) {
            var tags = data[key];
        }
        for(var i = 0; i < tags.length; i++){
            tag = tags[i];
            //console.log(tag['name']);
            $scope.tags_index += 1;
                    $scope.items.push({ 
                        tags_index: $scope.tags_index,
                        tag_name: tag['name'],
                        inlineChecked: false,
                        question: "",
                        questionPlaceholder: tag['name'],
                        text: ""
                    });
            $scope.form.g1tags = 'aaaaaaaaaaaaaaaaaaaaaaaaab';
            console.log ($scope.form.g1tags);

        }

    });
  }

the textfield only display the first character of 'aaaaaaaaaaaaaaaaaaaaaaaaab', anyone know what is the problem?

Upvotes: 0

Views: 47

Answers (2)

Will
Will

Reputation: 492

In your controller, you're assigning g1tags a single string value:

$scope.form.g1tags = 'aaaaaaaaaaaaaaaaaaaaaaaaab';

while in your view, you're accessing it as if it's a collection

form.g1tags[item.tags_index]

This isn't going to work-- if you need g1tags to hold multiple values, you should create an array:

$scope.form.g1tags = [];

//And then in your for loop:
$scope.form.g1tags.push('aaaaaaaaaaaaaaaaaaaaaaaaab');

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

Its because you are accessing only the first element inside ng-repeat, remove [item.tags_index] from ng-model

 <input type="text" placeholder="{{item.questionPlaceholder}}" ng-model="form.g1tags" required>

Upvotes: 1

Related Questions