我见过this https://stackoverflow.com/a/11972028/110233 and this https://stackoverflow.com/questions/12265565/angularjs-promise-is-resolved-before-data-is-loaded但似乎可能有一种更简单的方法。
在我看来,我有几个通过权限控制的菜单选项 - 即,并非每个人都可以看到“仪表板”视图。因此,在我看来,在我的菜单选项中,我有如下内容:
<li ng-show="validatePermission('Dashboard')">Dashboard</li>
在我的控制器中,我定义了一个 validatePermission 方法,它正在查看当前用户的权限。例如:
$scope.validatePermission = function(objectName) {
if $scope.allPermissions......
另外,在我的控制器中,我通过 $http 调用加载这些权限:
$http.get('permissions/' + userid + '.json').success(function(data) {
$scope.allPermissions = data;....
问题是在视图调用 validatePermission 之前 $scope.allPermissions 不会被加载。如何在视图渲染之前等待 allPermissions 加载?
You ask:
如何在视图渲染之前等待所有权限加载?
为了防止整个视图渲染,必须使用resolve。不过,您不必使用 Promise 库,因为 $http 返回一个 Promise:
var app = angular.module('app');
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'template.html',
controller : 'MyCtrl',
resolve : MyCtrl.resolve
});
});
function MyCtrl ($scope, myHttpResponse) {
// controller logic
}
MyCtrl.resolve = {
myHttpResponse : function($http) {
return $http({
method: 'GET',
url: 'http://example.com'
})
.success(function(data, status) {
// Probably no need to do anything here.
})
.error(function(data, status){
// Maybe add an error message to a service here.
// In this case your $http promise was rejected automatically and the view won't render.
});
}
}
但如果您只是想隐藏仪表板
,请按照 Joe Gauterin 的建议进行操作。这是一个非常简单的笨蛋例子 http://plnkr.co/mGX6OcEmy2OOsTl7u19q如果你需要的话。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)