Cameron Kilgore
Cameron Kilgore

Reputation: 423

Run an AngularJS method on page load

I have a custom scope method within a Controller, and when a custom directive loads, I want to run a method inside the defined controller. I've seen a lot of options, but which one could be referenced inside a template via an ng-* call? Otherwise, what are the best options?

Upvotes: 0

Views: 66

Answers (2)

Andreas Jägle
Andreas Jägle

Reputation: 12240

If you are on angular 1.5 already and can use the new component way to build your custom directive, you could use the newly introduced $onInit method instead of polluting the constructor, that should only initalize the object itself.

For details, please see this blogpost: https://toddmotto.com/on-init-require-object-syntax-angular-component/

Upvotes: 0

nathan.medz
nathan.medz

Reputation: 1603

Since the controller is instantiated when the directive is loaded, any method called in your controller will be called on page load. In my code it is often something like

angular.module('app')
    .controller('controllerName', ctrl);

function ctrl() {

/*--------Initialize--------*/
someMethod()
}

Upvotes: 2

Related Questions