user3384493 user3384493 - 5 months ago 16
AngularJS Question

ng-model and form inside ng-repeat

I am creating a form for each item in my $scope. ng-model is not linking with the data on my form submit.

<li ng-repeat="item in favourites">
<form ng-submit="DeleteFavourite()" class="form-horizontal" id="frmSpec">
<input ng-model="item.Description"/>
<input ng-model="item.Refno"/>
<button type="submit"class="btn">{{item.Description}}
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
</li>

Answer

The issue is very closely related to the comment by @DavidBeech . In an angular controller the scope is seen as a hierarchy object.

So for example if you have the following:

<div ng-controller="SomeCtrl">  
<li ng-repeat="item in favourites">
   <form ng-submit="DeleteFavourite()" class="form-horizonatal" id="frmSpec">
       <input  ng-model="item.Description"/>
       <input  ng-model="item.Refno"/>
       <button type="submit"class="btn">{{item.Description}}
           <span class="glyphicon glyphicon-remove"></span>
       </button>
   </form>
</li> 
</div>

When that controller is injected into the div and that new scope instance is created it only sees what is at that level and the scopes of it's parents. It has no knowledge of its children's scopes. Therefore, when you call DeleteFavourite() since it is a method attached to the scope of the controller it will not have the context of the ng repeat. So as David stated you will need to do something like DeleteFavorite(item) in order for it to have knowledge of what you are submitting otherwise you will not have knowledge of what item in the iteration you are submitting.

Feel free to comment if you want an example and I can put together a fiddle with an example of scope inheritance.