AngularJS run controller code when view is loaded / initialized

JavaScript

I want to run some initialization code in my controller when loading a view. I tried it with ng-init but I dont think this is a good approach:

<div ng-init="init()">
  My app
</div>

AngularJS controller:

$scope.init = function () {
    console.log('view ready');
}

I wonder if this is the right way to run some code in my controller once the view is loaded / ready.

Software Question created: 2020-05-05 05:46 IownU

3

In AngularJS you can use $onInit which is available on any AngularJS component: component lifecycle documentation. You can use it on a factories, controllers, services or modules.

var app = angular.module('app',[]);
app('SomeController', function ($scope) {

    //init state
    $scope.myVariable = '';

    //controller binding on view initialized
    this.$onInit = function () {
      $scope.myVariable = 'Hello World!';
    }
});

$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.

answered 2020-05-05 05:54 codeBrother