AngularJS UI Router - $state.current.name is empty when using templateUrl
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*)