Reputation: 2328
I have a page, with a number of items (rendered through ng-repeat), each one of these items holds a bunch of "read-only" data and a form.
I'm using the ng-form directive and naming them as in this question/answer
However where mine differs is I'm not putting ng-form on the repeated element as it doesn't "feel right" to have all the display fields/divs inside that form.
Instead my html looks like this:
<div ng-controller="MyController">
<div ng-repeat="inst in Repeats">
{{inst.name}}
<div>Loads of "read only" content here, including charts/custom directives</div>
<ng-form name=frm_{{$index}}>
<input type="text" ng-model="inst.name" />
</ng-form>
</div>
<input type="button" value="View scope in console" ng-click="View()" />
The problem is that I cannot get access to the forms on the scope in the controller. The answer to the question (linked above) shows that this naming convention works and I should see a number of objects on the $scope in the controller to get access to.
However as demonstrated in this plunk clicking the "View scope in console" button - shows the forms have not been added to the scope.
Do I need to change the structure of the html to have both the ng-repeat and ng-form on the same element for this to work??
Upvotes: 4
Views: 2981
Reputation: 2328
So, I've solved this.
What I did, which after looking around seems to be a fairly "standard" way of doing it, was to pass the form into the View() function on every call.
the html looks like this:
<div ng-controller="MyController">
<div ng-repeat="inst in Repeats">
{{inst.name}}
<div>Loads of "read only" content here, including charts/custom directives</div>
<ng-form name=frmInputs}>
<input type="text" ng-model="inst.name" />
</ng-form>
</div>
<input type="button" value="View scope in console" ng-click="View(frmInputs)" />
Note that the form does not get an "Unique name" in terms of the page (I'm not using {{$index}} to append to the form name anymore) - however as the ng-form is within a repeat - it is unique for each instance in that repeat. So I can pass "frmInputs" to the View() method on my controller - which will allow me access to the form that is currently being acted on.
Upvotes: 4