nuriffah
nuriffah

Reputation: 99

angularJS: Function in function

Hello I'm new in angularJS. Suitable or not to implement function inside function?

For example like this:-

$scope.loadDistrict = function(id) {
  // statement
  $scope.loadBasedOnYear = function(y_id) {
    console.log(y_id);
    // statement
  };
};

Upvotes: 0

Views: 62

Answers (3)

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

If you bind method on scope, it's available from view.

From your code

$scope.loadDistrict = function(id) {
  // statement
  $scope.loadBasedOnYear = function(y_id) {
    console.log(y_id);
    // statement
  };
};

loadBasedOnYear won't available until loadDistrict is called.

It's very bad pattern to follow.

Upvotes: 3

Mike Jerred
Mike Jerred

Reputation: 10525

Yes this is fine.

You should watch out for when the function will be executed outside of angular's cycle. E.g. if you do:

setTimeout(function() { $scope.test = 5; }, 1000);

If you need to do this then you need to wrap the function in $scope.$apply(), or use $timeout.

Upvotes: 0

Martijn Welker
Martijn Welker

Reputation: 5605

It is possible but without context I don't really know why you would do this, calling $scope.loadBasedOnYear before calling $scope.loadDistrict will result in an error so be careful with such a design pattern.

Upvotes: 0

Related Questions