P. Ruzic P. Ruzic - 1 month ago 7
AngularJS Question

AngularJS controller not called from html

If anyone can help, I'd be very thankful. I am pretty new to AngularJS and trying to learn it. The problem I got is that one of controllers are not called when button Bought is pressed

<div class="col-md-6" ng-controller="AlreadyBoughtController as Items">
<h2>Already Bought:</h2>
<ul ng-repeat="bought in Items.ItemsBought track by $index">
<li>Bought {{bought.quantity}} {{bought.name}}</li>
</ul>
<div class="emptyMessage" ng-if="Items.ItemsBought.length === 0">Nothing bought yet.</div>
</div>.


Please look complete code with app.js file on plunker:
http://plnkr.co/edit/8wKY7PPZ6mINsFGCJQfP?p=preview

Answer

That's because you were never actually passing the index of the item you bought.

<li>Buy {{item.quantity}} {{item.name}} <button class="btn btn-default" ng-click="itemsToBuy.boughtItems($index);"><span class="glyphicon glyphicon-ok"></span> Bought</button></li>

Pass $index to your function: ng-click="itemsToBuy.boughtItems($index);

Take a look at the fixed plunk.