Struggling with implementing a conditional template component within an AngularJS directive

As a Java/Python developer, I found myself working on an AngularJS project recently.

While most concepts were easy to grasp, some of the syntax and functionality still elude me.

The code I have handles login/logout functionality. If the user is logged in, it should show X. I am looking to make the template conditional.

if loggedIn
   show this
else
   show this

I understand that I need to use the template variable to set the generated HTML for the page. How can I achieve this?

This is the code snippet I aim to modify.

.directive('login', ['loginService', function(loginService) {
    return {
        restrict: "E",
        replace: true,
        template: '<div ng-show="session.loggedIn" class="loginwidget">Logged In: {{ session.username }} <button ng-click="session.logOut()">Log Out</button> </div>',
        //scope: { user: '=' },
        link: function(scope,element,attrs) {
            scope.session = loginService.session();
        }
    };
}])
;

The project uses AngularJS v1.0.8. I plan to upgrade it soon as the ng-if directive was introduced later which I believe will help solve some problems. Additionally, ensuring an up-to-date version of the AngularJS library is important to me.

Answer №1

Perhaps you are looking for something along these lines...

.directive('login', ['loginService', function(loginService) {
    return {
        restrict: "E",
        replace: true,
        template: 
            '<div> ' +
            '    <div ng-show="session.loggedIn" class="loginwidget"> ' +
            '        Logged In: {{ session.username }} <button ng-click="session.logOut()">Log Out</button> ' +
            '    </div>' +
            '    <div ng-show="!session.loggedIn" class="loginwidget"> ' +
            '        Logged Out <button ng-click="session.logIn()">Log In</button> ' +
            '    </div>' +
            '</div>',
        //scope: { user: '=' },
        link: function(scope,element,attrs) {
            scope.session = loginService.session();
        }
    };
}])
;

Another aspect you may want to consider is how scope.session will be affected when the user logs out.

This specific directive will connect with your parent controller and update accordingly when there are changes to scope.session in the parent component. Have you implemented code in the parent controller to manage the session when the user logs in or out?

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

showing the response message from a post request using Vue.js and Axios

Within APIService.js, there's a function: createPatient(data){ const url = 'http://192.168.1.3/api/clinic/patient/add/'; return axios.post(url, data).then(resp => {return resp}); } In the script tag of my vue component: result ...

NuxtJS using Babel 7: the spread operator persists in compiled files

Struggling to get my NuxtJS app functioning properly on IE11. Despite multiple attempts to configure Babel for compatibility, spread operators are still present in the built pages files, suggesting that Nuxt code is not being transformed correctly. Below ...

Unable to display PHP response in a div using AJAX - issue persisting

Hey there! I'm currently working on a project where I want the form submission to load a response into a div without refreshing the page. I've looked at various examples of ajax forms with PHP online, but haven't been able to solve my issue ...

The Functionality of Accordions

I have created a responsive accordion script that functions smoothly and allows for easy access to content within each drawer. Unlike many accordions, this one does not cause issues with positioning after opening. The code I am using includes a toggle acti ...

What is causing the error "Next is not a function" to occur when exporting a Middleware function to the module.exports object?

In my logger.js module, I have a middleware function that I import into app.js and utilize. // ------ File : logger.js ------ // function log(req, res, next) { console.log('Logging details ... '); next(); } module.exports = log; // ---- ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

The script is unable to locate the property 'indexOf' because it is undefined

Searching for a specific value in an array using ui-select to capture values. A function is created to verify the existence of the value, which works perfectly fine. However, the console displays multiple instances of the error 'Cannot read property & ...

Learn how to seamlessly connect lists in Vue with these foolproof steps

<template> <div class="lists"> <div v-for="(list, key, i) in getAllBreeds" :key="i"> <div v-if="list.length"> <div v-for="(ele,i) in list" ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...

Access the child element of a span by targeting a specific attribute value using Protractor

Trying to check if a popover appears using protractor. Below is the snippet of HTML code with the popover in the last child span: <span tariff-popover="views/popovers/c2g/airport.html" class="ng-isolate-scope"> <span ng-transclude=""> ...

Retrieve the binary file data that was sent via Postman using Node.js/Express.js

I am currently testing file uploading in my backend system. I am using Postman to send binary data as a file in the request body, and now I need to extract this data from the POST request. req.body The above code snippet returns a binary buffer that look ...

Reaching out to a particular individual with a message

In my coding dilemma, I am trying to make a bot send a message every minute to a particular user, not all users. The struggle is real! guild.members.cache.forEach(member => { setInterval(() => { member.send('hello').catch(error =&g ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Utilize the inverse mapping method along with conditional statements inside a mapping function

When looping through the categories using categories.map(), I am trying to reverse the elements of the categories and also check for category.isFeatured before creating a link. However, I am unable to use an if statement in this scenario. const Header = ...

End your Idp session and log out using passport-saml

Encountering a 400 bad request error when attempting to log out a user from the idp session. Despite successfully logging out the user from the application/passport session, they remain logged in to the idp session. The logout and callback endpoints are c ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

Utilizing BehaviourSubject for cross-component communication in Angular

My table is populated with data from a nodeJS API connected to methods inside my service. I attempted using a Behavior Subject in my service, initialized as undefined due to the backend data retrieval: Service: import { Injectable } from "@angular/core" ...

Utilizing AngularJS and Bootstrap popover: A guide to effectively implementing "popover-is-open" within an ng-repeat loop

When utilizing ng-repeat to generate a table with items, each item has a button in its row that opens a popover for editing the object. I want to avoid using the click-outside property of the bootstrap popover because I only want the popover to close when ...