Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have:

angular.module('someMod')
    .directive('premiumUser', premiumUser)
    .controller('PremiumUserCtrl', PremiumUserCtrl);

function premiumUser () {
    return {
        restrict   : 'A',
        link       : premiumUserLink,
        controller : 'PremiumUserCtrl',
    };
}

function premiumUserLink (scope, element) {
    if (!scope.checkLoggedIn())
        element.hide();
}

function PremiumUserCtrl ($scope, sessionManager) {
    $scope.checkLoggedIn = function () {
        return sessionManager.isUserLoggedIn();
    };
}

When I use this directive on an element like so:

<ANY premium-user></ANY>

it works, but the targeted directive's controller still initializes and executes onInit code.

Is there a way to modify this directive to prevent controller initialization?

Thank you in advance!

Answer №1

If my understanding is correct, using a ng-if should solve the issue. You can simply utilize a scoped variable to verify its availability, and then insert the scope.var on the directive tag within the template.

<any premium-user ng-if="iSGuest"></any>
/ / ctrl

$scope.isGuest = function() {
  //processing for guest
};

Answer №2

element.hide() simply adjusts the CSS property display: none, allowing directives and controllers to still initialize.

To address this, you could create a customized directive similar to ng-if:

function premiumUser ($animate) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 600,
        transclude: 'element',
        link: function(scope, element, attrs, ctrl, transclude) {
            if (scope.checkLoggedIn()) {
                var childScope;

                if (!childScope) {
                    childScope = scope.$new();
                    transclude(childScope, function(clone) {
                        $animate.enter(clone, element.parent(), element);
                    });
                }
            }
        },
        controller: 'PremiumUserCtrl'
    };
}

If you're curious about how it operates, take a look at the ngIf documentation and source code for more information.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Possibilities: Incorporating xlsx Files in Angular 5

Is there a way to read just the first three records from an xlsx file without causing the browser to crash? I need assistance with finding a solution that allows me to achieve this without storing all the data in memory during the parsing process. P.S: I ...

Tips for altering objects within an array

I am dealing with an array of objects that looks like this: const items = [ {name: 'Sam', amount: '455gbjsdbf394545', role: 'admin'}, {name: 'Jane', amount: 'iwhru84252nkjnsf', role: 'user'}, ...

Why do my paths encounter issues when I alter the manner in which I deliver my index.html file?

I recently made a decision to change the method of serving my index.html file from app.use('/', express.static(__dirname + '/..')); to app.get('/', function(req, res) { res.sendFile(path.join(__dirname + '/../index.htm ...

The jQuery mousedown() function seems to be malfunctioning and unable to trigger the drag event

I am attempting to initiate a drag event using jQuery. You can access the fiddle by clicking here http://jsfiddle.net/sgsvenkatesh/hepbob75/5/ I tried using the following code to initiate the drag event, but it doesn't seem to be working: $(documen ...

Modify the background color of checkboxes without including any text labels

I am looking to customize my checkbox. The common method I usually see for customization is as follows: input[type=checkbox] { display: none; } .my_label { display: inline-block; cursor: pointer; font-size: 13px; margin-right: 15px; ...

What is the average time frame for completing the construction of an electron project?

My project has only a few npm dependencies, but the build process is taking longer than 30 minutes and still counting. I'm not sure if this is normal or if there's an issue causing the delay. I have two specific questions: Is it common for pro ...

Fade in/out overlay effect when clicking on a content block

I've hit a roadblock while trying to implement overlay fading in and out to cover a block created by some JavaScript code. Here is a link to the project. When you click on any of the continents, a series of blocks with country flags will appear. You& ...

Mastering Vue 3: Simplifying a reactive array of objects while maintaining reactivity

Struggling with maintaining reactivity in Vue 3 when flattening a nested array of objects. Unfortunately, my attempts result in crashing and browser hang-ups. In my Vue 3 component, I have an array structured as a list of objects: this.grouped = [ ...

Is there a way to access the body html element within a template in vue.js?

I'm struggling to add styles to the body element of my HTML page. It seems like I can't access it directly from the template because there's another body element nested inside the main body. Even when I try to change the style using JavaScri ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

Are there any plugins available that can create a Ken Burns effect using JQuery?

All I need is a straightforward plugin, not one for creating slideshows. In this case, I only have 1 div and 1 image. The goal is to have the image animate within the div, shifting left/right or up/down without any white space visible. The size of the ima ...

A guide on testing mouse clientY in React using JEST for effective testing

useEffect(() => { const mouseHandler = (event: MouseEvent) => { menuData.forEach((element) => { if (element.hasActiveDropdown && event.clientY > 50) { handleCloseDropDown(); // handleDropDown('0') ...

Adding a task to my database successfully through Postman integration

I'm having trouble implementing the code for my todo app using React. I am encountering an issue with adding a new todo to the database using the handleSubmit function. Oddly enough, it works fine when testing with Postman, but not when trying to inpu ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

No content appearing instead of AngularJS code displayed

My goal is to retrieve data from a MySQL database using PHP and then pass that data in JSON format to AngularJS for display in a table. The HTML code looks like this: <body ng-app="myModule"> <div class="row"> <div class="col-lg-12 ...

Utilizing JSONP callbacks in Dart

I've been struggling with implementing basic JSONP in Dart and I can't seem to figure it out. After reading this specific blog post along with another helpful resource, it suggests using window.on.message.add(dataReceived); to receive a MessageEv ...

Incorporating `ngRepeat` to populate options within a <select> element

Attaching data to each row and modifying it based on conditions I want to attach data to each individual row in Angular and also be able to modify that data depending on certain conditions. <select id="subject" name="subject" ng-mo ...

A guide on how to associate data in ng-repeat with varying indices

Here is the data from my JSON file: var jsondata = [{"credit":"a","debit":[{"credit":"a","amount":1},{"credit":"a","amount":2}]}, {"credit":"b","debit":[{"credit":"b","amount":3},{"credit":"b","amount":4},{"credit":"b","amount":5}]}, {"credit":"c","debi ...

Clicking on the menu to reveal the dropdown options using JavaScript

I have created a drop-down menu for my website, but I am facing an issue. When I click on the links again, it does not work properly because I lack expertise in JavaScript. I would appreciate any help and suggestions from all of you. Thank you for your tim ...

Click event dynamically bound to list items

I have a web application built with Durandal and Knockout. Here is the HTML code snippet: <ul id="header"> </ul> In a JavaScript function, I am dynamically adding a list item as follows: $("#header).append('<li id="btn"><a hre ...