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?
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.
ng-app in AngularJS This is used to initialize an Angular. JS application.
Answer: ng-init is called whenever the template is re-rendered.
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.
Wait until the variable is init.
$scope.$watch('pageTitle', function () {
console.log($scope.pageTitle);
});
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?
the controller is being created before the pageTitle variable is added to the $scope object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With