Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS UI Router - $state.current.name is empty when using templateUrl

I am using ui router for Angular and trying to get the name of the current state.

After 3 days working on it, I found out that it is empty when I use templateUrl. After changing it to template: 'test', state name magically appears...

Is it possible to make it work? Here is the demo

Code on above link
like image 448
Arth Avatar asked Apr 29 '15 10:04

Arth


1 Answers

A $watch is needed here, because it's all asynchronous we can't rely on timing:

myApp.controller('navCtrl', ['$state', '$scope','$timeout', function($state, $scope, $timeout){
    $scope.currState = $state;
    console.log("This one have some objects: ");
    console.log('by reference:', $scope.currState);
    console.log('by value:', JSON.parse(JSON.stringify($scope.currState)));

    // console.log("But when I want to access name its empty: ");
    // $timeout(function() {
    //    console.log($state.current.name);
    // });

    // use this instead:
    $scope.$watch('currState.current.name', function(newValue, oldValue) {
      console.log(newValue);
    });  
}]);

The console.log('by reference:', $scope.currState); does work because that uses a reference to the object. By the time we see it in the console the object is already changed.

Compare with the output of console.log('by value:', JSON.parse(JSON.stringify($scope.currState))); above, which freezes the output at the point of execution. You'll find an empty $state.current.name.

Also see: How can I change the default behavior of console.log? (*Error console in safari, no add-on*)

like image 162
TijsH Avatar answered Sep 20 '22 01:09

TijsH