javascript - AngularJS : Two way binding inside directives -
i'm relatively new angularjs , i'm writing app. app has array of objects, each of objects has private variable called status. have 2 filters, return subset of these objects based on status. example, statuses corresponding these 2 filters 'new' , 'old' respectively.
next, i've written directive makes divs formed these objects, draggable. basically, directive receive object through 2 way data binding, , changes status of object calling corresponding method.
the problem is, changes in status of object doesn't update filter instantly. example, when drag 3 of divs other half, status gets updated, filter doesn't.
here's directive:
.directive('draggable', function ($document) { return { scope: { bill: '=' // bill object }, restrict: 'a', link: function (scope, element, attr) { // here console.log('bill', scope.bill); var startx = 0, starty = 0, x = 0, y = 0, sourcex = 0, sourcey = 0, windowwidth = 0; element.on('mousedown', function (event) { event.preventdefault(); startx = event.pagex - x; starty = event.pagey - y; $document.on('mousemove', mousemove); $document.on('mouseup', mouseup); windowwidth = $(window).width(); sourcey = event.pagey; sourcex = event.pagex; }); function mousemove(event) { y = event.pagey; x = event.pagex; element.css({ top: y + 'px', left: x + 'px' }); } function mouseup(event) { $document.unbind('mousemove', mousemove); $document.unbind('mouseup', mouseup); console.log('mouseup', startx, starty, event.screenx, event.screeny); var mid = windowwidth / 2; if (sourcex < mid && event.pagex >= mid) { // yes there change of sides scope.bill.markcooking(); // change status cooking console.log('moved cooking', scope.bill.getstatus()); } else if (sourcex >= mid && event.pagex < mid) { scope.bill.enq(); // change status new console.log('moved enq', scope.bill.getstatus()); } } } }})
what doing wrong here?
any time you're in browser event handler outside of angular's lifecycle. user's actions have triggered event, angular doesn't know needs check , update bindings (in case, bill status).
calling scope.$apply()
manually triggers angular's change detection, , update bindings:
scope.$apply(function() { if (sourcex < mid && event.pagex >= mid) { // yes there change of sides scope.bill.markcooking(); // change status cooking console.log('moved cooking', scope.bill.getstatus()); } else if (sourcex >= mid && event.pagex < mid) { scope.bill.enq(); // change status new console.log('moved enq', scope.bill.getstatus()); } });
you can read more scopes , lifecycle here: http://docs.angularjs.org/guide/scope
Comments
Post a Comment