8

Using AngularJS, is it possible to use the "onload" argument to trigger a function defined inside a "child" controller (a controller called by the included template)?

Example:

<!-- parent container -->
<div ng-include="'/path/template.html'" onload="childOnLoad()"></div>

<!-- template.html -->
<div ng-controller="childController">   
    <p ng-bind="txt"></p>
</div>

<!-- childController.js -->
app.controller('childController', function($scope) {    
    $scope.txt = "Test text";

    $scope.childOnLoad = function() {
        alert("Loaded!");
    };  
});

Does it make sense? Or should I simply call the function inside the childController, as in the following?

<!-- childController.js -->
app.controller('childController', function($scope) {    
    $scope.txt = "Test text";

    $scope.childOnLoad = function() {
        alert("Loaded!");
    };

    $scope.childOnLoad();   
});
4
  • Have a look at stackoverflow.com/questions/15458609/… Commented Mar 27, 2014 at 11:05
  • So... do you suggest to simply call $scope.childOnLoad() inside the child controller? Commented Mar 27, 2014 at 11:44
  • 1
    Yes I would just call the $scope.childOnLoad() function inside the controller. Until angular adds another directive specifically for onload events. Commented Mar 27, 2014 at 12:13
  • Another thing I'd like to mention is that if your childOnLoad function simily initializes variables, you might even be better off removing it altogther and initializing in the main body directly. Commented Mar 27, 2014 at 12:15

2 Answers 2

3

Leave the parent container the way you defined it:

<div ng-include="'/path/template.html'" onload="childOnLoad()"></div>

In the parent controller define:

$scope.childOnLoad() {
  $scope.$broadcast("childOnLoad", data);
}

and in the child controller:

$scope.$on("childOnLoad", function (event, data) {
  alert("Loaded!");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your example, I did not know I could do that, It saved my day, It worked fine when calling child controller from parent controller, thanks a lot.
2

In your second attempt you did right: you are creating some functions, the scope of that controller is taking those functions as properties, then $scope.childOnLoad(); will call the function you created.

In fact you can define so many functions but they are not called while loading or when loads complete.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.