angularjs - Angular directive intended to resize itself to match it's parent throws $digest() iterations error -
http://plnkr.co/edit/idjuctlz41wkusxpnvgk?p=preview
so have canvas directive, , want canvas fill it's parent div. tried like
app.directive('paperboard', function () { return { template: '<canvas></canvas>', replace: true, restrict: 'e', scope:true, link: function (scope, element, attrs) { var cv = element; var ctx = cv[0].getcontext("2d"); scope.boundsdim = function(){ return { 'width': element.closest('div').width(), 'height': element.closest('div').height() } }; scope.$watch(scope.boundsdim, function(nv,ov){ ctx.canvas.width = nv.width; ctx.canvas.height = nv.height; }); } }; });
problem is, seems go in sort of infinite loop , angular throws 10 $digest() iterations reached. aborting
error. ideas how fix it?
change code watching by reference watching collection contents.
scope.$watchcollection(scope.boundsdim, function(nv,ov){ console.log(nv); ctx.canvas.width = nv.width; ctx.canvas.height = nv.height-4; });
from docs:
watching by reference (scope.$watch
(watchexpression, listener)
) detects change when whole value returned watch expression switches new value. if value array or object, changes inside not detected. efficient strategy.watching collection contents (scope.$watchcollection
(watchexpression, listener)
) detects changes occur inside array or object: when items added, removed, or reordered. detection shallow - not reach nested collections. watching collection contents more expensive watching reference, because copies of collection contents need maintained. however, strategy attempts minimize amount of copying required.
-- angularjs developer guide -- scope watch depths.
your scope.boundsdim
function returns new object each time called. since $watch
watches by reference, calling listener function everytime.
also listener function increasing height 4 each time. changing ctx.canvas.height = nv.height-4;
stabilized height changes.
Comments
Post a Comment