I recently made a transition of my simple paging feature from the controller to a directive, but encountered a peculiar issue. Whenever I update the parent scope from within the directive, the changes only reflect on the next alteration. For instance, if the ng-options are [10,20,30] and I change it to 10, nothing happens. Then, when I switch it to 20, it reverts back to the previous value of 10, and so on.
Despite trying to use $scope.$apply, the updates still get delayed. I seem to be missing something here. It appears to be related to digest update and $scope.$apply, but I'm struggling to determine where exactly to apply it. Everything I attempt just doesn't seem to work.
The relevant sections in the controller:
vm.pages = 0;
vm.articles = [];
vm.load = { page: { batch: 10, current: 1 }
, sort: { _id: -1 }
, filter: {}
};
vm.getArticles = function() {
articleS.list(vm.load, function (data){
vm.pages = data.pages;
vm.articles = data.articles;
});
}
The directive:
.directive("paging", function() {
var scope = { update: '&', current: '=', pages: '=', batch: '=' };
function link(s, e, a) {
s.options = [10,20,50,100];
s.toPage = function(p) {
switch(p) {
case "last":
if (s.current != s.pages) {
s.current = s.pages;
s.update();
}
break;
case "next":
if (s.current < s.pages) {
s.current ++;
s.update();
}
break;
case "prev":
if (s.current > 1) {
s.current --;
s.update();
}
break;
default:
s.current = 1;
s.update();
}
}
}
return {
replace: true,
scope: scope,
templateUrl: 'paging.tpl',
link: link
}
});
The directive template:
<section class='pages'>
<select
ng-model="batch"
ng-change="toPage('first')"
ng-options="value for value in options">
</select>
<div>
<button ng-click="toPage('first')"> 1 </button>
<button ng-click="toPage('prev')"> << </button>
<div>{{current}}</div>
<button ng-click="toPage('next')"> >> </button>
<button ng-click="toPage('last')"> {{pages}} </button>
</div>
</section>
Directive call:
<paging
update="vm.getArticles()"
current="vm.load.page.current"
batch="vm.load.page.batch"
pages="vm.pages">
</paging>