4

How to use window.onload function inside a controller.

 window.onload= function() { 
    console.log("Hi Page loaded")
   };

The controller is not applicable for the full page. I want to execute a function after my controller loads at-least.

4
  • 1
    A controller is a function. Put code directly in that function, and it will be executed when the controller function is called by angular. Commented Dec 2, 2016 at 14:41
  • Angular functions will execute asynchronously. I want to run a particular function after all the other functions completes execution. Commented Dec 2, 2016 at 15:53
  • You really, really need to clarify your question. First you talk about window.onload. Then you say "after my controller loads". Then you say "after all the other functions completes execution", bu wothout saying what those other functions are. What are you trying to achieve, at a higher level? What would you like your controller to do? Commented Dec 2, 2016 at 16:01
  • window.onload will execute after page loads completely. So i wanted to use window.onload in my code. But my application is loading within another page. So the controller which i wrote is not for the full page. Thats why window.onload is not working. So alternate option i have is execute a function after all other function completes execution. Commented Dec 2, 2016 at 16:18

3 Answers 3

6

You can use ng-init and invoke your necessary function using the same directive

var app = angular.module('DemoApp', [])
app.controller('akuaController', function($scope) {
  $scope.load = function() {
    alert("Window is loaded");
  }
});
<!DOCTYPE html>
<html>

<head>
  <script data-require="[email protected]" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body ng-app="DemoApp" ng-controller="akuaController">
  <div ng-init="load()">
  </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

1 Comment

This is not waiting for the DOM being entirely loaded.
1

Changing the example from Angular $window

Your Controller

angular.module('windowExample', [])
    .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
      $scope.greeting = 'Hello, World!';
      $scope.doGreeting = function(greeting) {

        // This would be a starting point
        $window.onload(greeting);
      };
    }]);

Your markup

<div ng-controller="ExampleController" ng-init="ExampleController.doGreeting()">
</div>

Comments

1
//inside your controller

$scope.$on('$viewContentLoaded', function() {

    // write here

    // either methods or variables 

});

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.