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

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

Can you explain the definition of "mount" in the context of Express?

Currently diving into the world of Express.js, I stumbled upon this definition: "An Express router offers a limited set of Express methods. To initialize one, we call the .Router() method on the main Express import. To utilize a router, we mount it a ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

Traveling within a layered object

Currently, I'm working with an object and iterating through it to retrieve outputs as shown below: var obj = { "first": { "Bob": { "1": "foo", "2": "bar" }, "Jim": { "1": "baz" } }, "second": { "Bob": { ...

Activate the 'swipe back' feature within ion-item upon selecting ion-option-button

In my Ionic project, I created an ion-list with ion-items and added ion-option-buttons: <ion-list> <ion-item class="item " ng-repeat="exercise in exercises" on-double-tap="sendToChangeExercise"> <p><h2>{{exercise. ...

Experience an issue in your Ionic/Angular app with the `e.gesture` being undefined during Drag & Drop functionality. Additionally, explore the use of two separate Controllers

Currently, I am in the process of developing an application that requires the implementation of Drag & Drop functionality as a primary interaction feature. To provide a clearer picture, envision an Ionic Side Menu containing an <ion-list> displaying ...

if a condition is not being properly assessed

Currently, I am working on a $.ajax call to retrieve data in JSON format. Within this JSON data, there is an element called "status." My code snippet checks if the value of `data.status` is equal to "success" and performs some actions accordingly. Despite ...

What is the best way to title an uploaded chunk with HTML5?

Here is the script I am working with: function upload_by_chunks() { var chunk_size = 1048576; // 1MB function slice(start, end) { if (file.slice) { return file.slice(start, end); } else if (file.webkitSlice) { ...

Is it possible to generate a Token in Nexus for private packages without using the UI interface?

We have implemented Sonatype Nexus Repository ManagerOSS 3.29.0-02 and are currently facing an issue in generating a TOKEN that can be used with .npmrc following this specific structure: registry=http://NEXUS-IP:8081/repository/GROUP-NAME http://NEXUS-IP:8 ...

Guide to handling multiple forms within a single template using Express

If I have an index.html file containing two tables - "Customers" and "Items", along with two forms labeled "Add customer" and "Add item", how can I ensure that submitting these forms results in a new entry being added to the respective table as well as t ...

``Is there a more SEO-friendly option instead of using an iframe?

I am looking for a solution to easily share my content with other websites without the issues I currently face. Presently, I use an iframe which poses two problems: <iframe width=“540”; height=“700” frameborder=“0” src=“http://www.energi ...

The function auth.createUserWithEmailAndPassword is not recognized in the context of React

base.jsx: import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; const firebaseConfig = { config }; export const app = initializeApp(firebaseConfig); export const auth = getAuth(); Register.jsx ...

Is NextJS 13 the Key to App Directory On-Demand Revalidation?

I am looking to implement on-demand revalidation with next13 and the app directory. While I have successfully used the app-directory to replace the need for getServerSideProps or getStaticProps, there is one specific page on our site that needs to be rebui ...

Run module following a POST request

I am currently working on integrating real-time information transmission through sockets using socket.io, along with push notifications sent via the OneSignal platform. However, I have encountered an issue where placing both functionalities in the same mo ...

Error: The reference property 'refs' is undefined and cannot be read - Next.js and React Application

Here is my code for the index page file, located at /pages/index.js import { showFlyout, Flyout } from '../components/flyout' export default class Home extends React.Component { constructor(props) { super(props); this.state = {}; } ...

The ng-repeats functionality is triggered multiple times whenever I attempt to make this call

I have a situation where I am using ng-repeat in my Laravel view to call a function from the controller. This function retrieves data from the database, performs some calculations, and then returns an array. However, I am facing an issue where the data is ...

Avoid mentioning the controllerAs alias in your directive

I'm facing an issue with the following code snippet. Here is the simplified version of the problem: <div ng-controller='AController as a'> <div a-directive></div> </div> In my JavaScript file, I have defined: a ...

Using React with TypeScript to ensure that at least one key of a type is not null, even if all keys are optional

Within my Typescript code, I have defined an event type that includes various time parameters: export type EventRecord = { name: string; eta: string | null; assumed_time: string | null; indicated_time: string | null; }; I also have a func ...

AngularJS shows an error when attempting to access the property 'childNodes' of an undefined element

Recently diving into AngularJS, I incorporated bootstrap validator to ensure form validation in my project. Initially, everything was running smoothly until I introduced the following snippet into my controller's JavaScript file for validation: $(doc ...

What is the best way to arrange cards in a specific order with breaks in between each flip

I am currently working on creating flip cards using HTML and CSS. I have successfully implemented the hover effect which flips the cards when hovered over. Now, my goal is to make the cards automatically flip one after the other at specific time intervals ...