0

I have following trouble. I have several rows with dynamically generated inputs in AngularJS view. I'm searching elegant way to get array from this generated inputs. This is me html:

<div ng-app>

    <div ng-controller="TestCtrl">
         <input type="button" value="+" ng-click="addNewRow();"/>
        <div ng-repeat="item in items"><input type="text" name="key" ng-value="{item.name}"/> : <input type="text" ng-value="{item.value}"/>
            <input type="button"  value="x" ng-click="removeItem($index);"/>
        </div>

        <input type="button" value="Test" ng-click="showItems();"/>
    </div>
</div>

and this is my javascript code:

function TestCtrl($scope) {
    $scope.items = [
        {name: "", value: ""}
    ];

    $scope.addNewRow = function () {
        $scope.items.push({
            name: "",
            value: ""
        });
    };

    $scope.removeItem = function (index) {
        $scope.items.splice(index,1);
    };    

    $scope.showItems = function() {
        alert($scope.items.toSource());
    }
};

alert($scope.items.toSource()); will work correct only under Firefox and as you can see array is empty. I'm searching a way to update array or other angular way method. document.querySelector("input[attr]") or jQuery similar is not good idea I think.

Here is working jsFiddle: http://jsfiddle.net/zono/RCW2k/21/

I would appreciate any advice and ideas.

Best regards.

3
  • 1
    take a look at this Commented Jan 30, 2014 at 9:39
  • 1
    what do you mean by get array from this generated inputs? the array is $scope.items, you already can access it Commented Jan 30, 2014 at 9:42
  • 1
    do you need something like this: jsfiddle.net/6aQt7/1 ? Commented Jan 30, 2014 at 9:44

1 Answer 1

1

Use ngModel:

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

Your view should look like:

<div ng-repeat="item in items">
  <input type="text" ng-model="item.name"/> : 
  <input type="text" ng-model="item.value"/>
  <input type="button"  value="x" ng-click="removeItem($index);"/>
</div>

(As for the use of toSource() in your code, it is not part of any standard - Gecko-only)

Working example: http://jsfiddle.net/rgF37/

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. I know about that toSource is Gecko-only. I already write that this will work on Firefox only. Thank you for your help.

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.