Josh Davis Josh Davis - 4 years ago 240
Javascript Question

Angularjs ng-if with ajax request

I'm new to angularjs and trying to figure out how to show/hide navbar elements depending on permissions. I'm currently getting the permissions via an ajax request:

mycloudControllers.controller('HeaderController', ['$scope', '$http',
function($scope, $http) {
$http.get('/api/header').then(function(data) {
$scope = data.data;
console.log($scope);
});
}
]);


HTML:

<div ng-if="viewFiles || updateFiles" class="col-xs-12 col-sm-6 col-md-4 col-lg-3">


JSON Response (console.log):

{viewAccounts: true, viewAccountTypes: true, viewFiles: true, updateFiles: true}


The console logs the correct permissions (set to true) but I can't figure out how to get the compiler to wait until the request finishes to execute the ng-if. I want to use ng-if so the DOM elements are completely removed as opposed to just hidden.

I may be going about this the wrong way, so any light that can be shed would be greatly appreciated.

Answer Source

You are overwriting the entire scope. Try defining a property on it:

$scope.permissions = data.data
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download