Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to create a form that has a dynamic set of input boxes. I'm trying to get ng-models to work with array items and I am clearly doing something wrong.

My problem seems to be indexing the scope array lineItems in the template.

Here is my jsfiddle: http://jsfiddle.net/dk253/9ykuuobq/

Here is my code:

<div ng-controller="MyCtrl">
     <h2>Testing Arrays</h2>

    <button type="button" ng-click="addItem()" class="btn btn-primary">Howdy</button>
    <div ng-repeat="item in items" item="item" my-index="{{$index}}" itemlist></div>
</div>
<script type="text/ng-template" id="template.html">
    <div class = "row">
        <div class = "col-xs-6"> <input name= "itemNum-{{item.itemNum}}" type = "number" class="form-control"
            placeholder = "Item Number" ng-model="items[{{item.itemNum}}].itemNum" required> </div>
        <div class = "col-xs-6"> <input name= "name-{{item.itemNum}}" type = "text" class="form-control"
            placeholder = "Name" ng-model="items[{{item.itemNum}}].name" required> </div>
    </div>
</script>

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function ($scope) {
    $scope.count = 0;

    $scope.items = [];

    var baseItem = {
        itemNum: 0,
        name: "New"
    };

    $scope.addItem = function () {
        newItem.itemNum = $scope.count;
        var newItem = angular.copy(baseItem);
        newItem.itemNum = $scope.count;
        $scope.items.push(newItem);
        $scope.count += 1;
    };
});

myApp.directive('itemlist', function ($compile) {
    return {
        templateUrl: 'template.html',
        restrict: 'A',
        replace: true,
        transclude: true,
        scope: { item: '=', myIndex: '@' }
    };
});

Thanks for your help!

share|improve this question

1 Answer 1

up vote 1 down vote accepted

The fiddle has several mistakes:

  1. $scope.addItem is using the newItem before defining it. Remove the first line (probably a typo).
  2. The ng-model:
    1. It accepts expressions without {{...}}. So ng-model="items[{{item.itemNum}}].itemNum" would become ng-model="items[item.itemNum].itemNum"
    2. This is still wrong because the directive has isolated scope and the items variable is not visible. But item is visible, so you only need: ng-model="item.itemNum" (and ng-model="item.name").

With these changes, it seems to be working: http://jsfiddle.net/9ykuuobq/19/

share|improve this answer
    
Huge! Thanks Nikos, I appreciate it. (sorry for the typos) –  Dave Kearney Feb 8 at 18:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.