Utilize the ng-click
directive
<button ng-click="incrementCounter()">Click me</button>
Define an incrementCounter
function in the $scope
and then invoke a global method to update b
within the ngClick
handler.
angular.module('myapp')
.controller('MainCtrl', function ($scope) {
$scope.b = a;
$scope.incrementCounter = function(){
incrementCounter();
$scope.b = a;
};
});
Avoid defining functions in Global Scope. It is recommended to use Angular's service
or factory
instead.
var app = angular.module('myapp');
app.controller('MainCtrl', ['$scope', 'myFactory', function ($scope, myFactory) {
$scope.b = myFactory.getData();
$scope.incrementCounter = function () {
myFactory.incrementCounter();
$scope.b = myFactory.getData();
};
}]);
app.factory('myFactory', function ($http) {
var a = 0;
return {
incrementCounter: function () {
return a++;
},
getData: function () {
return a;
}
};
});