As I was working on the phone tutorial, I found myself pondering how to implement a specific use case.
- The browser renders a list of phones.
- When the user clicks on
add phone
for one of these phones, - the function
addItem
is triggered and adds that phone into the arrayphonesInCart
. - Then, the list with the phones in the cart (
$scope.phonesInCart = [];
) is updated.
You can check out the logic demonstrated in my codepen demo.
<body ng-controller="PhoneListCtrl">
<h3>Phones we sell</h3>
<ul class="phones">
<li ng-repeat="phone in phones | filter:query | orderBy:orderProp">
<b>{{phone.name}} </b>
<button ng-click="addItem(phone)"
ng-disabled="{{phone.orderReadonly}}">add phone</button>
</li>
</ul>
<h3>Phones in your cart</h3>
<ul>
<li ng-repeat="phoneInCart in phonesInCart">
{{phoneInCart.name}}
</li>
</ul>
</body>
Additionally, here's the relevant JavaScript code:
$scope.phonesInCart = [];
$scope.addItem = function(phone) {
// These lines do not affect the UI
phonesInCart.push(phone);
$scope.$apply();
}
Current Status
The list is rendered and the 'addItem' function is activated. However, at present, the list of phones in the cart is not being updated or displayed.
My Query
I am curious about:
- What needs to be done to populate a second array
phonesInCart[]
, refresh anotherng-repeat
? - Do I need to create/use more than one controller like
in order to enable a secondaryphonecatApp.controller('PhoneListCtrl'
ng-repeat
?