0

what is the difference between init() method calling from controller initialization time and from html page at rendering in angular js ?

html partial:

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

controller :

angular.module('masterJs')
    .controller('SignupCtrl', function ($scope, $rootScope) {

        $scope.init(){
          //code here
        }

    });

here i am calling init() method from partial. what is the difference when we call init() from controller not from the html page like:

angular.module('masterJs')
        .controller('SignupCtrl', function ($scope, $rootScope) {

            $scope.init(){
              //code here
            }


          $scope.init();
        });

2 Answers 2

1

The difference is that when you have the ng-init in the HTML, the init() function will only be called during the actual render of the page. If for any reason that content needs to be re-rendered, the init() function will be called again.

When you call the init() function on the controller, it will only run one time (when the controller is created). According to angular's documentation, this is the best practice (avoid using ng-init).

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

Comments

1

Normally you use ng-init for intitializing a ng-repeat.

The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

Example:

<script>
angular.module('initExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.list = [['a', 'b'], ['c', 'd']];
  }]);
</script>
<div ng-controller="ExampleController">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
     <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  </div>
</div>
</div>

The way you are using the init function, is inappropriate.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.