javascript - ngRepeat track by: How to add event hook on model change? -
i have simple ngrepeat following:
<some-element ng-repeat="singlerecord in arrayofrecords track singlerecord.id"> <!-- stuff --> </some-element>
arrayofrecords
updated server , may contain new data.
ngrepeat
's track by
feature can figure out when new element added array , automatically updates dom without changing existing elements. hook code , execute callback function when there's new data coming in or old data removed. possible via angular?
from understand, there's $$watchers
triggers callbacks whenever there's changes variables, don't know how go hacking that. right direction?
note: know can manually save arrayofrecords
, compare new values when fetch them see changed. however, since angular offers track by
feature has logic, nice if can have angular automatically trigger event callback when element added or removed array. doesn't make sense duplicate logic exists in angular.
probably create directive , add along ng-repeat, directive when created(when item added ng-repeat) emit event , when item destroyed emit event.
a simple implementation here:
.directive('tracker', function(){ return{ restrict:'a', link:function(scope, el, attr){ scope.$emit('item_added', scope.$eval(attr.tracker)) scope.$on('$destroy', function(){ scope.$emit('item_removed', scope.$eval(attr.tracker)) }); } } });
and use as:
<some-element ng-repeat="singlerecord in arrayofrecords track singlerecord.id" tracker="item">
and listen these events @ parent controller example.
or using function binding in different way, without using isolate scope that.
.directive('tracker', function() { return { restrict: 'a', link: function(scope, el, attr) { var setter = scope.$eval(attr.tracker); if(!angular.isfunction(setter)) return; setter({status:'added', item:scope.$eval(attr.trackeritem)}); scope.$on('$destroy', function() { setter({status:'removed', item:scope.$eval(attr.trackeritem)}); }) } } });
the 1 above specific question since there no other built in way, note if find out items added/removed, in controller diffing 2 lists. try use lodash api _.unique
or simple loop comparisons find results.
function finddif(oldlist,newlist){ return {added:_.uniq(newlist, oldlist), removed:_.uniq(oldlist, newlist)}; }
Comments
Post a Comment