javascriptangularjsdjango-rest-frameworkangularjs-digestangularjs-ng-include

Angular HTTP Requests to Render Different HTML


So I have a rest endpoint at the URL /check which returns serialized user data like so:

{
    'username' : 'malikb',
    'email': 'test@gmail.com',
    'first_name': 'Malik',
    'usertype': 'C'
}

I've designed my endpoint to return a 401 status code for users that are not logged in and 200 status code for users that are, and that works fine. However, I'm trying to use Angular's $http service to extrapolate both the status code and the usertype key if available.

Essentially, I'm trying to use <ng-include> render a different navigation bar for anonymous users that are logged in and different ones for those that are logged in depending on their user type. However, the issue that I'm running into is the fact that the requests are asyncronous. Furthermore, ng-if and src attributes for my included HTML seem to evaluate continuously thereby sending thousands of HTTP requests. Is there any way to achieve such a feature?


Solution

  • Avoid using asynchronous functions in HTML templates as they evaluate every digest cycle. Avoid tangling concerns of Model and View. The View should only render the Model. The Controller modifies the Model using user events from the View and events from elsewhere.

    MVC

    app.controller('ctrl', function($http) {
        var vm = this;
        this.$onInit = function() {
            vm.userData = { username: 'anonymous' };
            $http.get("/check").then(function(response) {
                vm.userData = response.data;
            });
        };
    });
    
    <user-navbar ng-hide="vm.userData.username == 'anonymous'></user-navbar>
    <anon-navbar ng-show="vm.userData.username == 'anonymous'></anon-navbar>