可以使用自定义JavaScript函数通过ng-click更新任何字段。为此, 我们可以在HTML(通常是按钮)中创建一个可点击的对象, 然后附加一个ng-点击调用此自定义函数的指令。 AngluarJS中的ng-click指令用于单击元素时应用自定义行为。它可以用于显示/隐藏某些元素, 或者在单击按钮时可以弹出警报。
语法如下:
<element ng-click="expression"> Contents... </element>
示例1:此示例在单击按钮后调用一个函数来更改字段值。
<!DOCTYPE html>
<html ng-app = "example">
<head>
<title>
How to directly update a field
by using ng-click in AngularJS?
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body>
<div ng-controller = "basicCntrl">
<h1 style = "color:green">
Hello {{name}}!
</h1>
<!-- on button click the change()
function is called from $scope -->
<button type = "button"
ng-click = "change()">
Click!
</button>
</div>
<script type = "text/javascript">
var app = angular.module('example', []);
app.controller('basicCntrl', function($scope) {
$scope.name = "GFG";
$scope.change = function() {
this.name = 'lsbin';
}
});
</script>
</body>
</html>
输出如下:
在单击按钮之前:

单击按钮后:

该按钮调用更改更改变量名称的函数。该更改反映在页面上, 因为{{名称}}句法。对于更简单的逻辑(如示例1中所示的逻辑), 我们可以避免在ng-click指令内调用函数并更改变量。
示例2:本示例在ng-click指令中更改变量名称。
<!DOCTYPE html>
<html ng-app = "example">
<head>
<title>
How to directly update a field
by using ng-click in AngularJS?
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body>
<div ng-controller = "basicCntrl">
<h1 style = "color:green">
Hello {{name}}!
</h1>
<!-- on button click the name is changed directly -->
<button type = "button"
ng-click = "name='lsbin'">
Click!
</button>
</div>
<script type = "text/javascript">
var app = angular.module('example', []);
app.controller('basicCntrl', function($scope) {
$scope.name = "GFG";
});
</script>
</body>
</html>
输出如下:
在单击按钮之前:

单击按钮后:

另外, 我们可以使用其他HTML标记来使ng-click起作用, 例如段落标记。
示例3:本示例使用一个段落标签来更改标题内容。
<!DOCTYPE html>
<html ng-app = "example">
<head>
<title>
How to directly update a field
by using ng-click in AngularJS?
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js">
</script>
</head>
<body>
<div ng-controller = "basicCntrl">
<h1 style = "color:green">
Hello {{name}}!
</h1>
<!-- on paragraph click the name is changed directly -->
<p ng-click = "name='lsbin'">
Click!
</p>
</div>
<script type = "text/javascript">
var app = angular.module('example', []);
app.controller('basicCntrl', function($scope) {
$scope.name = "GFG";
});
</script>
</body>
</html>
输出如下:
在点击参数元素"点击"之前:

单击参数元素"点击"后:
