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?

3
  • 1
    that's because console.log() returns undefined, then you return that value as controller. Commented Sep 4, 2013 at 7:51
  • 1
    Have you missed the correct fiddle? Commented Sep 4, 2013 at 7:54
  • @ssilas777 apologies, please check again. Commented Sep 4, 2013 at 7:59

4 Answers 4

36

Wait until the variable is init.

$scope.$watch('pageTitle', function () {
    console.log($scope.pageTitle); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

I prefer $timeout(function () { /* ... */ });
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?

Comments

12

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

Comments

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();
});

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.