0

I'm trying to get a native javascript event listener inside an AngularJs controller. I don't try to explain why but I cant' understand how to solve this.

I've created the custom event like this:

var event = document.createEvent('HTMLEvents');
event.initEvent('custom-event', true, true);
document.dispatchEvent(event);

and inside the angular controller:

angular.module('uploadCtrl', [])
  .controller('uploadController', ['$scope', '$window', '$compile', function($scope, $window, $compile, $http, Video) {
    document.addEventListener('custom-event', function(e) {
      console.log('event received');
    })
  }]);

What I'm doing wrong? Thanks

1 Answer 1

1

Keep in mind that the controller code is not going to execute until the DOM is ready. Without more code, it's hard to say what your issue is specifically, but I'll bet that you're firing off that event before the controller's wired up a listener. Take a look at this, which works.

(function(window, angular) {
  'use strict';

  angular.module('Test', [])
    .controller('UploadCtrl', ['$window', function($window) {
      $window.document.addEventListener('custom-event', function(e) {
      $window.console.log('event received');
    });
  }]);

  window.setTimeout(() => {
    const event = document.createEvent('HTMLEvents');
    event.initEvent('custom-event', true, true);
    document.dispatchEvent(event);
  }, 0);
})(window, window.angular);

Note that this code is just for demonstration purposes. The setTimeout' is only used to show that the event listener will handle the event, and that the OP's code is suffering from a race condition.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks to your answer, I've noticed that I didn't load the controller inside the application. Thanks mate
No problem. If my answer helped, please consider marking it as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.