等到范围变量加载后再在angular.js的视图中使用它

Art*_*kel 31 promise angularjs

我已经看过这个这个,但似乎可能有一个更简单的方法.

在我看来,我有几个菜单选项,通过权限控制 - 即,不是每个人都可以看到"仪表板"视图.所以在我的菜单选项中,我有以下内容:

<li ng-show="validatePermission('Dashboard')">Dashboard</li>
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我定义了validatePermission方法,它正在查看当前用户的权限.例如:

  $scope.validatePermission = function(objectName) {
    if $scope.allPermissions......
Run Code Online (Sandbox Code Playgroud)

同样在我的控制器中,我通过$ http调用加载这些权限:

  $http.get('permissions/' + userid + '.json').success(function(data) {  
    $scope.allPermissions = data;....
Run Code Online (Sandbox Code Playgroud)

问题是$ scope.allPermissions在视图调用validatePermission之前没有加载.如何在视图呈现之前等待allPermissions加载?

Ric*_*lly 21

你问:

如何在视图呈现之前等待allPermissions加载?

要防止整个视图呈现,必须使用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.
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

但如果你只是想隐藏仪表板<li>,那就像Joe Gauterin建议的那样.如果您需要,这是一个非常简单的示例plunkr.


Joe*_*oeG 10

没有加载validatedPermission时函数返回false allPermissions.这样,在加载ng-show之前,不会显示包含您的元素allPermissions.

或者,放在ng-show="allPermissions"封闭<ul><ol>.


luc*_*uma 6

您还可以在routecontroller上指定一个解析对象,该对象将在呈现该路由之前等待该对象解析.

来自角度文档:https: //docs.angularjs.org/api/ngRoute/provider/$routeProvider

resolve - {Object.=} - 应该注入控制器的可选依赖关系映射.如果这些依赖项中的任何一个是promise,它们将在实例化控制器并触发$ routeChangeSuccess事件之前被解析并转换为值.地图对象是:

key - {string}:要注入控制器的依赖项的名称.factory - {string | function}:如果是string,那么它是服务的别名.否则,如果是函数,则将其注入,并将返回值视为依赖项.如果结果是一个promise,则在将其值注入控制器之前解析它.

谷歌小组参考:https: //groups.google.com/forum/#!topic/angular/QtO8QoxSjYw