Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until scope variable is loaded before using it in the view in angular.js

I've seen this and this but it seems like there might be a simpler way.

In my view I have several menu options that are controlled through permissioning - i.e., not everyone can see a "Dashboard" view. So in my menu option in my view I have something like the following:

<li ng-show="validatePermission('Dashboard')">Dashboard</li> 

In my controller I have a validatePermission method defined where it is looking at the permissions of the current user. For example:

  $scope.validatePermission = function(objectName) {     if $scope.allPermissions...... 

Also in my controller I'm loading those permissions via an $http call:

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

The issue is that $scope.allPermissions doesn't get loaded before the view makes the call to validatePermission. How can I wait for allPermissions to be loaded before the view renders?

like image 701
Arthur Frankel Avatar asked May 17 '13 20:05

Arthur Frankel


2 Answers

You ask:

How can I wait for allPermissions to be loaded before the view renders?

To prevent the entire view from rendering, you must use resolve. You don't have to use the promise library though, since $http returns a 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.     });   } } 

But if you simply want to hide the dashboard <li>, then do as Joe Gauterin suggested. Here's a very simple example plunkr if you need it.

like image 79
Rick Jolly Avatar answered Oct 04 '22 23:10

Rick Jolly


Have the validatedPermission function return false when allPermissions hasn't been loaded. That way the element with your ng-show won't be displayed until allPermissions has been loaded.

Alternatively, put an ng-show="allPermissions" on the enclosing <ul> or <ol>.

like image 29
JoeG Avatar answered Oct 05 '22 00:10

JoeG