Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 594
jetcom Avatar asked Sep 04 '13 07:09

jetcom


People also ask

What is ng-init in AngularJS?

The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.

Is used for initializing the AngularJS variables?

ng-app in AngularJS This is used to initialize an Angular. JS application.

When Ng-INIT is called?

Answer: ng-init is called whenever the template is re-rendered.

What is variable in AngularJS?

Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component.


3 Answers

Wait until the variable is init.

$scope.$watch('pageTitle', function () {
    console.log($scope.pageTitle); 
});
like image 60
Dmitry Paloskin Avatar answered Oct 07 '22 02:10

Dmitry Paloskin


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?

like image 15
Ben Avatar answered Oct 07 '22 00:10

Ben


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

like image 12
Anton Avatar answered Oct 07 '22 02:10

Anton