Prasad Kanaparthi
Prasad Kanaparthi

Reputation: 6563

How to prevent calling a function on every action in angularjs

I am new to angularjs. I've a control like below

'use strict';
app.controller('userController', ['$scope', 'userService', function (scope, userService) {

$scope.user = {};

getUser();               // PROBLEM

function getUser() {
     // Logic
};

$scope.updateUser= function (user) {
    // Logic
};
}]);

Problem: The getUser() function is executing when i am calling updateUser function. How to prevent getUser() method to call on init and whenever i required.

Is there any mechanism like if(!Page.IsPostBack) in angularjs.

Upvotes: 1

Views: 2528

Answers (1)

random
random

Reputation: 7891

In front-end,

call the function using ng-click or ng-change events on the field you require-

<button type="submit" ng-click="getUser()" class="btn btn-primary">Click Me
</button>

And in Controller,

$scope.getUser = function () {
  console.log('In getUser');
}

To call the function on page-load, use init-

'use strict';
app.controller('userController', ['$scope', 'userService', function (scope, userService) {

$scope.user = {};

$scope.getUser = function(){

};

function init(){
  $scope.getUser();
}

init();
}]);

Upvotes: 3

Related Questions