AngularJS Events

May sariling HTML event directive ang AngularJS.

AngularJS Events

Maaari kang magdagdag ng event listener ng AngularJS sa iyong HTML element gamit ang isang o ilang sa mga sumusunod na instruction:

  • 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

Ang event instruction ay nagbibigay sa amin ng kapangyarihan na magsagawa ng AngularJS function sa ilang mga pangyayari ng user.

AngularJS 事件不會覆蓋 HTML 事件,兩個事件都會被執行。

鼠标事件

當光標移動到元素上時,將按照以下順序發生鼠標事件:

  • ng-mouseover
  • ng-mouseenter
  • ng-mousemove
  • ng-mouseleave

或者,當鼠標點擊元素時,將按照以下順序觸發:

  • ng-mousedown
  • ng-mouseup
  • ng-click

您可以在任何 HTML 元素上添加鼠標事件。

Example

當鼠標移動到 H1 元素上時,增加 count 參數:

<div ng-app="myApp" ng-controller="myCtrl">  
<h1 ng-mousemove="count = count + 1">鼠标移到我上方!</h1>  
<h2>{{ count }}</h2>  
</div>  
<script>  
var app = angular.module('myApp', []);  
app.controller('myCtrl', function($scope) {  
  $scope.count = 0;  
});  
</script>

Try It Yourself

ng-click 指令

ng-click 指令定義了當元素被點擊時將執行的 AngularJS 代碼。

Example

<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>

Try It Yourself

你也可以引用一個函數:

Example

<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>

Try It Yourself

切換,真/假

如果你想在点击按钮時顯示一部分 HTML 代码,并在再次点击按钮時隱藏,就像下拉菜單一樣,請使按鈕表現得像切換開關一樣:

点击我

Example

<div ng-app="myApp" ng-controller="myCtrl">  
<button ng-click="myFunc()">点击我!</button>  
<div ng-show="showMe">  
  <h1>菜单:</h1>  
  <div>披薩</div>  
  <div>意大利面</div>  
  <div>海鲜</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>

Try It Yourself

showMe 變量開始時為布爾值 false

myFunc 函數通過使用 !(非)運算符,將 showMe 變量設置為與其當前值相反的值。

$event 對象

調用函數時可以將 $event 对象作为參數傳遞。

$event The object contains the browser's event object:

Example

<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="myFunc($event)">Move the mouse over me!</h1>
<p>Coordinates: {{x + ', ' + y}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myFunc = function(myE) {
    $scope.x = myE.clientX;
    $scope.y = myE.clientY;
  }
});
</script>

Try It Yourself