我正在为Angular使用ui路由器并尝试获取当前状态的名称.
经过3天的工作,我发现当我使用templateUrl时它是空的.
将其更改为模板后:’test’,状态名称神奇地出现……
它可以使它工作吗?
Here is the demo
Code on above link
这里需要一个$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); }); }]);
console.log(‘by reference:’,$scope.currState);确实有效,因为它使用对象的引用.当我们在控制台中看到它时,对象已经被更改.
与console.log的输出进行比较(‘by value:’,JSON.parse(JSON.stringify($scope.currState)));上面,它冻结了执行点的输出.你会发现一个空的$state.current.name.
另见:How can I change the default behavior of console.log? (*Error console in safari,no add-on*)