我的菜单有指令。 在$ rootScope中,我设置了公司和用户权限。 根据所选公司和权限我呈现菜单。
我在app.run函数中设置了公司和用户权限。到目前为止,这有效,但有时菜单指令在服务调用完成之前呈现。 服务获取调用完成后是否有可能呈现菜单指令?
由于
app.run(function($rootScope, $http, $stateParams, $state, $q, goliathCompanyCheck)
{
....
....
....
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
var company_id = toParams.company_id;
if (company_id) {
var perm = goliathCompanyCheck.get({object: company_id},
function(response){
if (!response || !response.status || response.status == 'ERROR') {
$state.go('company_selector');
}
$rootScope.currentCompany = response.data.company;
},
function(response){
$state.go('company_selector');
});
}
});
});
答案 0 :(得分:1)
我建议使用UI-Router而不是在运行块中的rootscope上执行此操作。
这允许您将其指定为视图的依赖项。这样,除非解决了CurrentCompany,否则您的视图将无法加载,否则将触发状态更改失败。
在这个示例中,您的州' app'是您的应用程序的基本状态,并且在URL中需要公司ID,以便您可以为视图解析CurrentCompany。在app.html中,您可以拥有菜单组件的所有标记和指令,而您的页面可以是“应用程序”的子视图。 state意味着他们也可以访问CurrentCompany依赖项。
查看文档here
angular.module('app')
.config(function ($stateProvider) {
$stateProvider
.state('app', {
url: '/:companyId/'
templateUrl: 'app.html',
controller: 'AppCtrl',
resolve: {
//State won't resolve until CurrentCompany does
CurrentCompany: function ($stateParams, goliathCompanyCheck) {
return goliathCompanyCheck.get({object: $stateParams.companyId});
}
}
})
.state('app.home', {
url: 'home/',
templateUrl: 'home.html',
controller: 'HomeCtrl'
})
})
.controller('AppCtrl', function ($scope, CurrentCompany) {
//CurrentCompany gets injected into the controller and you can assign it to scope
$scope.CurrentCompany = CurrentCompany;
})
.controller('HomeCtrl', function ($scope, CurrentCompany) {
//Can inject it into the child state as well if you want
//but it's still available on the scope if the view is nested
})