AngularJS UI路由器 - 使用templateUrl时$ state.current.name为空

Art*_*rth 7 state angularjs angular-ui-router

我正在为Angular使用ui路由器并尝试获取当前状态的名称.

经过3天的工作,我发现当我使用templateUrl时它是空的.将其更改为模板后:'test',状态名称神奇地出现......

它可以使它工作吗? 这是演示

Code on above link
Run Code Online (Sandbox Code Playgroud)

小智 11

这里需要一个$ watch,因为它是异步的,我们不能依赖于时间:

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);
    });  
}]);
Run Code Online (Sandbox Code Playgroud)

console.log('by reference:', $scope.currState);确实有效,因为它使用对象的引用.当我们在控制台中看到它时,对象已经被更改.

console.log('by value:', JSON.parse(JSON.stringify($scope.currState)));上面的输出进行比较,它会在执行时冻结输出.你会发现一个空的$state.current.name.

另请参阅:如何更改console.log的默认行为?(*Safari中的错误控制台,没有附加组件*)