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?
-
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.JB Nizet– JB Nizet2016-03-07 20:09:05 +00:00Commented 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...Andreas Jägle– Andreas Jägle2016-03-07 20:20:57 +00:00Commented Mar 7, 2016 at 20:20
Add a comment
|
2 Answers
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()
}
2 Comments
Cameron Kilgore
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 }); }; });nathan.medz
just putting
$scope.load_records() anywhere in your controller will cause that method to be called when the controller is loadedIf 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/