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 of working on this, I found that it is empty when I use templateUrl. After you change it to the template: "test", the state name will appear ...

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

Code on above link 
+6
source share
1 answer

Here we need a $ A clock, because we cannot count on all asynchronous clocks:

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

console.log('by reference:', $scope.currState); works because it uses an object reference. By the time we see it in the console, the object has already been changed.

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

Also see: How to change the default console.log console behavior? (* Safari error console, without add-in *)

+10
source

Source: https://habr.com/ru/post/986216/


All Articles