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
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*)
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