i am new to AngularJS so please forgive me this dump question.
How do I listen to 'dom' events like 'click' or 'mousemove'?
This is what I got (No errors, but also no result in the console)
// Code is based on the orginal angularjs-seed.
angular.module('myApp.controllers', []).
controller('MyCtrl1', ['$scope', function($scope) {
$scope.$on('dragover', function() {
console.log('dragover');
});
$scope.$on('click', function() {
console.log('click');
});
}])
.controller('MyCtrl2', [function() {
}]);
@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.
element() Function in AngularJS is used to initialize DOM element or HTML string as an jQuery element. If jQuery is available angular. element can be either used as an alias for the jQuery function or it can be used as a function to wrap the element or string in Angular's jqlite. Syntax: angular.element(element)
AngularJS includes certain directives which can be used to provide custom behavior on various DOM events, such as click, dblclick, mouseenter etc. The following table lists AngularJS event directives. Event Directive. ng-blur.
$viewContentLoaded is fired as soon as the ui-view has the template compiled, and the controller has been executed.
In AngularJS, events are usually handled by the directives.
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM.
For the "click" event you would use ngClick directive:
HTML:
<button ng-click="doSomething()">Click me</button>
JS:
function MyCtrl($scope){
$scope.doSomething = function(){
// do something...
};
}
For the "dragover" event (and other events which are not already covered with Angular native directives) you would write your own directive:
HTML:
<div drop-target>Drop here</div>
JS:
angular.module('MyApp')
.directive('dropTarget', function(){
return function($scope, $element){
$element.bind('dragover', function(){
// do something when dragover event is observed
});
};
})
ngClick and ngMouseover are supported out of the box, but you will need to write your own directive for drag events, or better yet, use a third party module that's already been written. I managed to get this drag and drop module working for my code:
https://www.npmjs.org/package/angular-draganddrop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With