An Old Guy and His Dog
An Old Guy and His Dog

Reputation: 499

AngularJS - directive with a dynamic array of objects in form

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!

Upvotes: 0

Views: 1562

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40298

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/

Upvotes: 1

Related Questions