我需要在运行时动态地将子状态 Hook 到根状态。将 $state
注入(inject)服务似乎已到位,但 $state.state
被评估为 undefined
。但是 $state
返回有效的对象。如何解决?
app.service('EntryStateUrlService', ['$state', '$q', '$http', function($state,$q,$http){
this.getEntryStateUrl = function(feeds) {
var deferred = $q.defer();
var idx = 0,
promises = [];
feeds.forEach(function(e) {
$http.jsonp(e.link).success(function(data) {
var generatedStateName = data.title;
$state.state('root.' + generatedStateName, // $state.state is evaluated
{ // as undefined
templateUrl : '/partials/article-view.html', // here taking template
controller: function($scope){ // controller to pass
$scope.title = data.title; // values to this template
$scope.author = data.author;
}
})
});
});
/*stuff*/
}
}]);
最佳答案
尝试检查这些问答:
- AngularJS - UI-router - How to configure dynamic views
- AngularJS - Dynamic Default nested views from Json Data not appearing
我们通常可以看到:我们引用 $stateProvider
在config()
阶段...然后在 run()
中使用它阶段:
config()
阶段
var $stateProviderRef;
app.config(function ($stateProvider) {
$stateProviderRef = $stateProvider;
});
run()
阶段
app.run(['$q', '$rootScope', '$state', 'menuItems',
function ($q, $rootScope, $state, menuItems) {
// get some data somehow .. via $http
menuItems
.all()
.success(function (data)
{
// here we iterate the data
angular.forEach(data, function (value, key) {
// here we do DYNAMICALLY insert new states
$stateProviderRef.state(value.name, value);
});
$state.go("home")
});
}]);
关于angularjs - 如何使用 ui-router 在运行时 Hook 新的子状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323191/