AngularJS Events
Chúng ta có thể `bắt các sự kiện (event listener)` diễn ra trên các phần tử HTML bằng cách sử dụng các tiền chỉ lệnh (directives) của AngularJS như sau:
ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-paste
The event directives allows us to run AngularJS functions at certain user events.
An AngularJS event will not overwrite an HTML event, both events will be executed.
Mouse Events
Mouse events occur when the cursor moves over an element, in this order:
- ng-mouseover
- ng-mouseenter
- ng-mousemove
- ng-mouseleave
Or when a mouse button is clicked on an element, in this order:
- ng-mousedown
- ng-mouseup
- ng-click
You can add mouse events on any HTML element.
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse over me!</h1>
<h2>{{ count }}</h2>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
The ng-click Directive
The ng-click directive defines AngularJS code that will be executed when the element is being clicked.
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunction()">Click me!</button>
<p>{{ count }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
});
</script>
Toggle, True/False
If you want to show a section of HTML code when a button is clicked, and hide when the button is clicked again, like a dropdown menu, make the button behave like a toggle switch:
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunc()">Click Me!</button>
<div ng-show="showMe">
<h1>Menu:</h1>
<div>Pizza</div>
<div>Pasta</div>
<div>Pesce</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.showMe = false;
$scope.myFunc = function() {
$scope.showMe = !$scope.showMe;
}
});
</script>
|