34

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?

Rishabh
  • 3,752
  • 4
  • 47
  • 74
jetcom
  • 955
  • 5
  • 13
  • 20

4 Answers4

36

Wait until the variable is init.

$scope.$watch('pageTitle', function () {
    console.log($scope.pageTitle); 
});
DimaOverflow
  • 1,513
  • 1
  • 16
  • 18
15

You can also take advantage of how JavaScript defines functions and use a function for ng-init instead of $watch (jsfiddle).

<div ng-app>
    <div ng-controller="MyCtrl" ng-init="pageTitleEquals('kittens')">
        Page title is {{ pageTitle }}
    </div>
</div>

Controller:

var MyCtrl = function($scope) {   
    $scope.pageTitleEquals = function(title) {
        $scope.pageTitle = title;
    }
};

This question is similar: How to set scope property with ng-init?

Community
  • 1
  • 1
Ben
  • 2,143
  • 2
  • 19
  • 27
12

the controller is being created before the pageTitle variable is added to the $scope object.

Anton
  • 7,709
  • 5
  • 31
  • 33
3

Since you are doing a "single time init", like a constructor I recommend you to unbind the watch after using the variable:

var pageTitleWatch = $scope.$watch('pageTitle', function () {
    console.log($scope.pageTitle);
    // Now just unbind it after doing your logic
    pageTitleWatch();
});
Renato Mefi
  • 2,131
  • 1
  • 18
  • 27