Search code examples
javascriptangularjsangularjs-directiveangular-directive

Angular directive remove element binding


I've got a directive which has a special handler foo for images that cause an error. foo updates the source of the bad image with the default image. It's got a binding as follows:

element0.bind('error', foo);

The problem is, if the default image source causes an error, foo is called infinite-ly.

Is there a way to kill the binding after it's called once? Among other things, I've tried

  • deleting foo
  • re-binding to null
  • deleting the return value from .bind()

Any ideas? I'll probably redesign this but the question remains nonetheless.


Solution

  • element0.unbind('error', foo);
    

    This answer is specific to jQuery, but it is the same for Angular jqLite.

    As for jQuery, bind and unbind are obsolete in favour of on and off.

    The arguments against usage of jQuery in Angular apply to this case. It is preferable to stick to scope events instead:

    var errorListener = $scope.$on('error', foo);
    

    And the listener is removed with

    errorListener();