0

I'm new to AngularJS I would like to string together the contents of several input text boxes. I have this fiddle:

<script>
    function MyController($scope){
        $scope.fields = {
            test : [{value: "aaa"}, {value:"bbb"}, {value:"ccc"}]
        }
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields.test">
            <input type="text" ng-model="field.value">
        </li>
    </ul>
    <pre>{{fields}}</pre>
</div>

http://jsfiddle.net/f3do0LLa/

I would like the value to be: aaabbbccc (also how can I adjust the code in for scenario where there could be x input boxes) Thanks

3 Answers 3

1

You have to iterate your fields value like you do for your input text.

<span ng-repeat="field in fields.test">{{field.value}}</span>

Demo

I used span tag instead of pre because it has a default line break.

If you want to keep pre render, you can style it:

<pre ng-repeat="field in fields.test" style="display: inline;">{{field.value}}</pre>
Sign up to request clarification or add additional context in comments.

Comments

0

Its also possible to iterate using a function, in my opinion it could be more flexible and allows you to do more complex actions with the inputs.

<script>
    function MyController($scope){
        $scope.fields = {
            test : [{value: "aaa"}, {value:"bbb"}, {value:"ccc"}]
        }
        $scope.fieldsCombined=function(){
        var res='';
          angular.forEach($scope.fields.test, function(value, key) {
                     res+=value['value'];
                });
          return res;
        }
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields.test">
            <input type="text" ng-model="field.value">
        </li>
    </ul>
    <pre>{{fieldsCombined()}}</pre>
</div>

Comments

0

http://jsfiddle.net/6jvLyg0p/ This is in case you want the concateneted string in a new model

html:

<script>
    function MyController($scope){

        $scope.fields = {
            test : [{value: "aaa"}, {value:"bbb"}, {value:"ccc"}]
        }
        $scope.$watch('fields', function(newVal){
        var tempModel = "";

        angular.forEach(newVal.test,function(val){

        tempModel = tempModel.concat(val.value);
        });
            $scope.modelNew = tempModel
        },true);
    };
</script>
<div ng-app ng-controller="MyController">
    <ul>
        <li ng-repeat="field in fields.test">
            <input type="text" ng-model="field.value">
        </li>
    </ul>
    <pre>{{fields}}</pre>
    <span>{{modelNew}}</span>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.