(This is not one of those "Oh I forgot $scope.$apply()
" problems)
Question is: How can I achieve live binding with ng-repeat
and a reactive helper function in the controller?
Let's focus on the code:
index.js:
<body ng-controller="AppCtrl as app">
<!-- (...) -->
<div class="dashboard" ng-controller="DashboardCtrl as ctrl">
<ul ng-repeat="timer in app.timers">
<li>{{timer.entry.title}}</li>
</ul>
</div>
</body>
AppCtrl.js:
angular.module('spectroscope').controller('AppCtrl', ['$scope', '$reactive', '$interval',
function($scope, $reactive, $interval) {
var me = this;
// Making this reactive
$reactive(this).attach($scope);
me._timers = {};
$.each(Entry.find().fetch(), function(idx, entry) {
me._timers[entry._id] = new Timer(entry, $interval);
});
/**
* Function for creating a new entry
*/
me.createEntry = function() {
let entry = new Entry(),
titleField = me.addEntryContainer.find('input[name=title]');
// Create new entry
entry.title = titleField.val();
entry.save();
// Create a new timer
let timer = new Timer(entry, $interval);
me._timers[entry._id] = timer;
};
// Reactive helpers
this.helpers({
/**
* Returns all timer objects
*/
timers: function() {
let timers = [];
$.each(me._timers, function(id, timer) {
timers.push(timer);
});
return timers;
}
});
}]);
Everything is working as expected: The timers for the time tracking app start and stop accordingly, and the time elements are updated in the <li>
s when the timers are running.
The issue: When a new timer/entry is added (AppCtrl.createEntry()
), it doesn't appear in the list. The ng-repeat directive doesn't call the helper function again to update the list.
Using $scope.$apply()
is not an option here as it's already in process due to the method being called by a ng-submit
directive.
Switching the _timer
field with a ReactiveVar
also does not solve the problem.