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?
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.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With