Example: To change the string value with ng-click in AngularJs
The below example adds a click listener(ng-click) to the button that changes the value of the name variable defined initially as Saurabh. The variable used wherever gets updated instantly.
<head>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="second">
<div ng-controller="app">
<h1 style="color:blue">
Hello {{name}}!
</h1>
<button style="padding:20px"
ng-click="name='Adarsh'">
Click Me
</button>
</div>
<script type="text/javascript">
var app = angular.module('second', []).controller('app',
function($scope) {
$scope.name = "Saurabh";
});
</script>
</body>
Output:
Example: to calculate the sum of two numbers and update directly in the view
The following example demonstrates addition that updates the sum field
<head>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="second">
<div ng-controller="app">
<input type="number" ng-model="a" >
<input type="number" ng-model="b" >
<button style="padding:20px"
ng-click="sum=a+b">
calculate sum
</button>
<h3 ng-init="sum=0">{{sum}}</h3>
</div>
<script type="text/javascript">
var app = angular.module('second', []).controller('app',
function($scope) {
$scope.a=0;
$scope.b=0;
});
</script>
</body>
FAQs
-
What is a directive?
Directives are markers for HTML dom elements that add a particular function or behaviour to the event listeners to that element. The ng-init directive adds and initializes a variable to its scope. ng-repeat is used to repeat HTML elements over a loop. Many more such directives exist like ng-if,ng-show,ng-bind.
-
Can a function be triggered from ng-click in AngularJs?
Ng-click in AngularJs can trigger a function defined in its scope that contains the behaviour or action we want.
$scope.count=0;
$scope.increment=function(){
$scope.count=$scope.count+1;
}
<element ng-click=”increment()”> </element>
<p>{{count}}</p>
You can also try this code with Online Javascript Compiler
Run Code
Key Takeaway
Congratulations on making it here. With this article, you learned how to update a field in your view with an ng-click in AngularJs. You got to see the concept behind directives with examples. You also saw multiple examples of how ng-click in AngularJs changes the fields in the view.
Check out this problem - Subarray Sum Divisible By K
You can learn about AngularJS for free by starting here Learn AngularJs.