0

My data model is something like the following

records
└─ record
   └─ id: 0
   └─ name: "Foo"
   └─ property: true
└─ record
   └─ id: 1
   └─ name: "Bar"
   └─ property: false
└─ record
   └─ id: 2
   └─ name: "Baz"
   └─ property: true

And I want to create a user interface to it using something like the following:

<div class="row">
  <input type="hidden" value="0"></input>
  <input type="text" value="Foo"></input>
  <input type="checkbox" checked></input>
  <button>Remove</button>
</div>
...

I am using angular for my project, and the code snippet I have is

<div ng-controller="ThingsController">
  <div class="row" ng-repeat="thing in things" ng-controller="ThingController">
    <input type="hidden" ng-model="id"></input>
    <input type="text" ng-model="name"></input>
    <input type="checkbox" ng-model="property"></input>
    <button ng-click="remove()">Remove</button>
  </div>
 </div>

with the following controllers:

angular.module('mymodule', [])
.controller('ThingsController', function($scope) {

  $scope.things = [{
    id: 0,
    name: "Foo"
    property: true
  }, {
    id: 1,
    name: "Bar"
    property: false
  }, {
    id: 2,
    name: "Baz"
    property: true
  }];

  $scope.remove = function(idx) {
    $scope.things.splice(idx, 1);
  };

  $scope.add = function() {
    $scope.things.push({
      id: $scope.things.length,
      name: 'Placeholder',
      property: true
    });
  };
})

.controller('ThingController', function($scope) {

  $scope.remove = function() {
    $scope.$parent.remove($scope.$index);
  };
});

This code doesn't work - a new set of input fields are created when we push to ng-repeat, but the models are not connected up correctly. When I inspect the situation, I see that there are actually 2 scopes, one for the ng-repeat and within this another for the ng-controller.

My question is: what am I doing wrong? Do I need to not use a new controller? Does anyone use this pattern to create variable length forms?

1 Answer 1

1

When accessing the object inside the ng-repeat, you have to use like thing.id, think.name, think.property and so on.

<div ng-controller="ThingsController">
  <div class="row" ng-repeat="thing in things">
    <input type="hidden" ng-model="thing.id"></input>
    <input type="text" ng-model="thing.name"></input>
    <input type="checkbox" ng-model="thing.property"></input>
    <button ng-click="remove($index)">Remove</button>
  </div>
 </div>

and place your remove function inside your ThingsController

$scope.remove = function(index) {
    $scope.things.splice(index, 1);
};

You really do not need ThingController.

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

1 Comment

This is it. I did read the documentation on ng-repeat, but just didn't spot how it linked to my case. Thanks for the quick response!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.