0

I am new to angular.

Why my ng-init variable is not overriding in controller?

<div ng-init="name='Emmad'" ng-controller="TodoController as todoCtrl" >
     <my-name></my-name>
</div>

my controller is:

App.controller('TodoController',['$scope',function($scope){
    $scope.name = "Zahid";
}]);

and my directive is :

App.directive('myName',function(){
    return {
        restrict: 'EA',
        template: '<b>{{name}}<b>'
    }
});

The output is always:

Emmad

It should be 'zahid' because I am using the directive in controller and controller will override the name variable.

Questions:
1-Why its not 'zahid'?
2-If I put breakpoint on

$scope.name = "Zahid";

I don't see 'name' variable in $scope why?

Emmad Zahid
  • 438
  • 6
  • 15

1 Answers1

0

Thanks @Pankaj Parkar for detailed answer here and below is the excerpt of answer.

Technically, what happening is that the ng-init directive gets evaluated after the ng-controller function gets registered. That's why initialized values from the ng-init are not available inside the controller.

Basically, the reason behind ng-controller getting called first is the priority. If you look at the priority, the ng-init directive has 450 & the priority option of directive, where ng-controller directive has 500, while compiling the directive from the DOM AngularJS sorts them as per priorities. Thus ng-controller gets executed first.

Community
  • 1
  • 1
Emmad Zahid
  • 438
  • 6
  • 15