Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-include: onload calling a function defined in included controller

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();   
});
like image 801
Matteo Piazza Avatar asked Mar 27 '14 10:03

Matteo Piazza


2 Answers

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.

like image 156
greenfox Avatar answered Oct 18 '22 22:10

greenfox


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!");
});
like image 27
Marco Lackovic Avatar answered Oct 18 '22 23:10

Marco Lackovic