0

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?

2
  • If you want something to happen when a directive is used, why don't you put that code in the directive? The directive shouldn't be aware of the controller controlling the template that uses the directive. Commented Mar 7, 2016 at 20:09
  • It sounds as if you want to run some code defined in your controller as soon as a directive is initialized. Could you please add some more details on the use case to your question for us to understand better what you want to achieve. Probably there is a better way of handling this... Commented Mar 7, 2016 at 20:20

2 Answers 2

2

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()
}
Sign up to request clarification or add additional context in comments.

2 Comments

How would I do this if I have a function declared inside my existing Controller? This is how its declared right now, for review. The $scope method is the method I want to run when this controller loads. app.controller(TestController', function($scope, $http) { $scope.load_records = function () { //Code goes here }); }; });
just putting $scope.load_records() anywhere in your controller will cause that method to be called when the controller is loaded
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.