jetcom jetcom - 1 month ago 18
AngularJS Question

Why is the variable set in ng-init undefined in $scope in AngularJS?

I have a variable I'm setting in my view with

ng-init
which I am then trying to access in my controller. When I try to access it however, I'm getting an
undefined
.

Relevant pieces of code:

My view:

<div ng-controller="MyCtrl">
<div ng-init="pageTitle = 'kittens'">
</div>
</div>


My controller:

var MyCtrl;

MyCtrl = function($scope) {
return console.log($scope.pageTitle);
};


JSFiddle

What am I missing here?

Answer

Wait until the variable is init.

$scope.$watch('pageTitle', function () {
    console.log($scope.pageTitle); 
});