2

As mentioned on title, I have small issue to assign new variable with $rootScope variable.

I have variable $rootScope.adulttotTicket with value 2. the value is int. So what I want is just to assign new variable newVal to $rootScope.adulttotTicket variable.

<p data-ng-init="newVal = $rootScope.adulttotTicket"></p>

but when I output variable newVal, it show nothing on my browser. So I try to edit at plunker, so I found out the value newVal is undefined. I don't have any idea what to do here.

newVal should easily have value 2 from $rootScope.adulttotTicket. but I got nothing. see on this plunkr plunkr

Hope get idea from anyone. thanks !

Fai Zal Dong
  • 323
  • 6
  • 25
  • Just wanted to mention that what you are trying to do sounds like a bad idea - as we all know, [gobal state is evil](http://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil) and ng-inits are too. Not saying there are no cases where its needed, but it should generally be a sign to rethink your design. – LionC Feb 10 '17 at 10:36
  • You should use `controllers` rather than `ngInit` to initialize values on a scope. – lin Feb 10 '17 at 10:38
  • It shows `adulttotTicket: 2 newVal: unassigned` I guess thats what you need right? – Prasanth Bendra Feb 10 '17 at 10:47
  • We had this strange bug and the only thing work is convert a variable to object. like $rootScope.ticket.adulttotTicket – Ishan Fernando Mar 02 '21 at 07:16

2 Answers2

1

Access $rootScope in view by using $root instead:

<p data-ng-init="newVal = $root.adulttotTicket"></p>

I updated your plunkr and it does work fine.

lin
  • 17,956
  • 4
  • 59
  • 83
0

When referring to $rootScope in a view use $root instead:

<p data-ng-init="newVal = $root.adulttotTicket"></p>

UPDATE

The reason why the above does not work is because you are not in a scope and so have no $scope to access the $root of! To fix you can declare your variable on the $rootScope in a run block as follows:

angular.module('myModule').
run(function($rootScope) {
    $rootScope.adulttotTicket = 'unassigned';
});

You can then access this in the view (with no reference to $root or $rootScope) as follows:

<p data-ng-init="newVal = adulttotTicket"></p>
Matthew Cawley
  • 2,688
  • 1
  • 8
  • 19