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

Combine array elements in Angular/Javascript based on a certain condition

Is there a way to combine elements from two arrays while avoiding duplicates? array = [ {id: 1, name:'abc'},{id: 1, name:'xyz'},{id: 2, name:'text1'},{id: 2, name:'text2'} ]; The desired output is: result = [{id: ...

Calculating the sum in a VueJS pivot table

Currently, I am delving into VueJS and working on migrating a basic application from Laravel with the blade template engine. The backend remains unchanged, consisting of a straightforward RESTful API with 3 tables: Books, Places, and a pivot table named B ...

Steps for redirecting from a URL containing location.hash to a different page

Recently, I decided to move a section of one of my webpages from dummy.com/get-started/#setup to its own page at dummy.com/setup. After making this change, I went ahead and deleted the old /get-started page on my website. Many people have bookmarks saved ...

Generate Random Quotes - Each new quote should be different from the previous one

As I tackle the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, everything seemed to be running smoothly except for one major issue - the same quote was often generated two or three times in a row. Obviously, this i ...

Is there a way for my extension to prevent a rickroll from starting before the video even begins?

I'm working on creating a Chrome extension that prevents rick rolls. Here's an overview of my manifest.json file: { "name": "AntiRick", "version": "1.0", "description": "Introduci ...

Steps for creating a resizable and automatically hiding side menu

I am working on a side menu that can be resized, and I want it to collapse (set to zero width) when it is empty. I have considered implementing one of these features individually, but I'm not sure how to make both work together. Is there a way to ad ...

Dropping challenging shapes in a block-matching game similar to Tetris

I'm currently working on a game similar to Tetris, but with a twist. Instead of removing just one line when it's full, I want to remove all connected pieces at once. However, I've run into a roadblock when trying to implement the hard-drop f ...

What is the process to access array elements in AngularJS?

When coding in HTML, <select class="element-margin-top" ng-model="vm.selectedRole" ng-options="(roleName,enabled) in vm.roleNames"> <option value="">All Roles</option>{{vm.roles[0]}} </select> I am tryin ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

What is the reason behind appending a timestamp to the URL of a JavaScript resource?

$script.ready('jui',function() { $script('<?php base_path(); ?>js/partnerScripts.js?ts=1315442861','partners'); }); Can anyone explain why there is a fixed ts=timestamp at the end of the partnerScripts.js file name? I ...

Press the AngularJS button using just JavaScript and the element

I've been developing a browser extension that automatically clicks buttons on web pages, but I've run into an issue with sites using AngularJS. The code functions properly on most websites except for those built with AngularJS. Below is the snip ...

Angular JS appears to be causing the DOM to freeze up while utilizing the ng-repeat directive to loop through

I have a current app where clicking a button triggers an $http request to fetch and return some data. The retrieved information is then used to update the $scope variables rows and columns, which are then looped through using ng-repeat. However, I've ...

New example of how to use the "useSession" syntax in Next Auth

Currently, I am delving into the next-auth documentation and feeling perplexed by the syntax used in the useSession hook. The way it's showcased in the documentation is as follows: const { data: session, status } = useSession() My confusion stems f ...

Verify if an element with a specific index exists within an array

$.each(constructions, function(i,v) { if ($.inArray(v.name, map[ii].buildings) == -1) {//do something} }; In this scenario, the constructions array consists of unique objects with a name attribute. On the other hand, map[ii].buildings is an array contain ...

Experiencing an issue with the Web Crypto API in NextJS due to receiving the error message "crypto is not defined."

I was wondering if NextJS supports the use of the web crypto API. Recently, I attempted to utilize it by writing the following code: crypto.subtle.digest('SHA-256', data) However, I encountered an error message that said: ReferenceError: crypto ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...

Can you explain the distinctions between using this['key'] and $data['key'] in the context of v-model?

Take a look at the snippet below, which includes three demos. The first two demos are functioning correctly (v-model is working fine). However, in the last demo, when you type something into the <input>, you will notice that this['test 1'] ...

Issue with Angular JS: ng-repeat not refreshing within ng-view

Whenever I make changes to the data stored in the variable $scope.userMovies, ng-repeat fails to update when it is inside an ng-view. Strangely enough, if it's placed outside of ng-view, everything updates as intended. What could be the reason behind ...

Tips for limiting the frequency of Angular provider loading instances

I have created a provider (I tried with a controller as well, but got the same results). Here is my code: .provider('socketio', function() { this.socket = io.connect("//localhost); console.log("LISTENING..."); this.$get = function() ...

Feeling overwhelmed by the potential capabilities of Angular Firestore

Seeking clarification as I am struggling to understand the usage of Angular and Firestore. Recently delved into Google Firebase and attempted CRUD operations with Firestore. What sets apart this library from others? import { Firestore } from '@angul ...