Reputation: 8166
I'm trying to learn AngularJS (along with Ionic Framework) and have got stuck because I can't get my page to reflect new items.
I use ng-repeat to display items on a page.
I have a delete item button which works.
When I click delete, that single item disappears off the page. All good so far.
However, when I try to add/push a new item nothing happens. If I debug in chrome and inspect the TimeEntries array I can see that the item IS being added to the array, but the page doesn't update to display the new item.
I don't understand why my deleteItem works perfectly fine, but testAdd does not work
Simplified code below.... In my html I have:
<ion-list ng-controller="EntriesCtrl">
<ion-item ng-repeat="entry in model.TimeEntries">
<div class="row">
<div>{{entry.JobCode}}</div>
<div>{{entry.Description}}</div>
<div>{{entry.MinutesSpent}}</div>
</div>
<ion-option-button ng-click="deleteItem(entry, $index)">
</ion-option-button>
</ion-item>
</ion-list>
<a ng-click="testAdd()">Add New</a>
In my controller I have:
$scope.model = {
TimeEntries: [
{ Id: 1, Date: new Date(), JobCode: 'JobCode.123', Description: "Blah blah blah", TimeSpent: 15 },
{ Id: 2, Date: new Date(), JobCode: 'JobCode.1', Description: "Blah blah", TimeSpent: 25 },
{ Id: 3, Date: new Date(), JobCode: 'JobCode.12', Description: "Blah blah blah", TimeSpent: 45 },
{ Id: 4, Date: new Date(), JobCode: 'JobCode.3', Description: "Blah blah blah", TimeSpent: 115 }
]
};
$scope.testAdd = function () {
$scope.model.TimeEntries.push({ Id: 5, Date: new Date(), JobCode: 'JobCode.1', Description: "Blah blah", TimeSpent: 25 });
}
$scope.deleteItem = function (entry, index) {
$scope.model.TimeEntries.splice(index, 1);
}
Pyetras' solution is correct but I have a follow-up question.
In my app.js I define the page as using the EntriesCtrl
.state('app.timesheetDay', {
url: "/timesheet-day/{date}",
views: {
'menuContent': {
templateUrl: "templates/timesheet-day.html",
controller: 'EntriesCtrl'
}
}
})
Because I defined that page to use EntriesCtrl, I thought any function called from that page would automatically be in the correct scope?
Why wasn't testAdd() firing under the correct scope in my above example?
After fiddling around it looks like if I remove the ng-controller attribute then the original testAdd works perfectly fine, so I guess I was narrowing/breaking the scope by defining it both in my state config and in the page attribute
Upvotes: 0
Views: 1582
Reputation: 1502
Your add button is outside the scope of the controller, move it inside the controller element like this:
<ion-list ng-controller="EntriesCtrl">
<ion-item ng-repeat="entry in model.TimeEntries">
<div class="row">
<div>{{entry.JobCode}}</div>
<div>{{entry.Description}}</div>
<div>{{entry.MinutesSpent}}</div>
</div>
<ion-option-button ng-click="deleteItem(entry, $index)">
</ion-option-button>
</ion-item>
<a ng-click="testAdd()">Add New</a>
</ion-list>
Upvotes: 3