ng-init is not getting the scope values initially

All we need is an easy explanation of the problem, so here it is.

I am calling a function on ng-init. this function takes the values from the scope.
Actually what happening is we load a page and on page load we use ng-init

<div ng-init="somefunction(c,d)">
</div>

$scope.somefunction = function() {
  console.log($scope.a);
}

$scope.abc = function() {
  //calling another function 
  $scope.xyz();
}
$scope.xyz = function() {
  $scope.a = "hello";
}
$scope.abc();//called on controller load

But I am not getting a in console means getting undefined. But after clicking on any button on page or some stuff. I got a. Means I am not getting this on page load.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You have to call it as

<div ng-init="somefunction()">
</div>

Besides that there are chances that you might get undefined if ng-init is called before $scope.abc()

Method 2

Make sure the scripts are loaded before the javascript functions. Otherwise you would get the values to be undefined.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <div ng-init="somefunction()">
  </div>
</div>
<script>
  var app = angular.module('myApp', []);
  app.controller('myCtrl', function($scope) {
    $scope.somefunction = function() {
      $scope.abc();
      console.log($scope.a);
    }

    $scope.abc = function() {
      //calling another function 
      $scope.xyz();
    }
    $scope.xyz = function() {
      $scope.a = "hello";
    }

  });
</script>

Method 3

Instead of using ng-init, you can directly call function in controller.
Something Like this :

<div></div>
$scope.a = '';
$scope.somefunction = function() {
  console.log($scope.a);
}

$scope.abc = function() {
  //calling another function 
  $scope.xyz();
}
$scope.xyz = function() {
  $scope.a = "hello";
}
$scope.abc();//called on controller load
$scope.somefunction();

It will simplify the process as it will execute only when everything is loaded and defined.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply