Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user.

angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) {
    return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
            scope.$watch(SessionTool.user, function (value, oldValue) {
                var list = attrs.deny.split(',');
                if (SessionTool.hasAnyRole(list))
                    return elem.hide();
                return elem.show();
            });
        }
    }
}]);

The issue I am facing is that when I log in, the $watch function does not trigger again to show the previously hidden element.

A summary of my SessionTool can be found below.

angular.module('app.tools').factory('SessionTool', ['$cookies', function ($cookies) {
    var _cookieKey = 'user';

    return {
        user: {},
        init: function () {
            var u = $cookies.get(_cookieKey);
            try {
                u = angular.fromJson(u);
                this.user = u;
            } catch (e) {
                console.log('invalid json');
            }
        },
        login: function (u) {
            this.user = u;
            $cookies.putObject(_cookieKey, u, {path: '/'}); // @TODO encrypt the whole JSON before saving it to cookies.
        },
        ...
    };
}]);

Can anyone explain why the $watch isn't triggering as expected?

Thank you in advance.

Answer №1

It appears that your directive is currently observing an anonymous variable SessionTool.user in the directive's scope, rather than the actual variable. To address this issue, I recommend implementing the following approach:

angular.module('app.tools').factory('SessionTool', ['$cookies','$rootScope', function ($cookies) {
var _cookieKey = 'user';
var _user = {};

return {

    setUser: function(user) {
       _user = user;
       $rootScope.$broadcast('SessionToolChange');
    },
    getUser: function() {
       return _user;
    },
    init: function () {
        var u = $cookies.get(_cookieKey);
        try {
            u = angular.fromJson(u);
            this.user = u;
        } catch (e) {
            console.log('invalid json');
        }
    },
    login: function (u) {
        this.user = u;
        $cookies.putObject(_cookieKey, u, {path: '/'}); // @TODO encrypt the whole JSON before saving it to cookies.
    },
    ...
};

}]);

angular.module('app.directives').directive('deny', ['SessionTool', function(SessionTool) {
        return {
            restrict: 'A',
            controller: function(scope, elem, attrs) {
                scope.$on('SessionToolChange', function(value, oldValue) {
                    // Retrieve the user and perform necessary actions.
                });
            }
        }
    }]);

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

Verify the presence of values in several textarea fields with jQuery before executing a specified action

My main goal is to validate multiple dynamic forms on a single page. If all textareas are either empty or contain default values, I need a specific function to be executed. However, if any of the textareas have content that deviates from the default value, ...

execute the execCommand function following an ajax request

I am currently developing a WYSIWYG editor and encountering an issue with image handling using execCommand. Here is a simplified example of my page structure: <div id="buttons_panel"><input id="img_submit" type="button"/></div> <div ...

How can the label value be updated in a material ui slider component?

code snippet: https://codesandbox.io/s/runtime-worker-kxse3?file=/src/App.js Can anyone help me ensure that the labels in the bubble display the same values as the text (3, 5, 7, 10)? ...

Tips for integrating the connect-orientdb module with the Express framework

My objective is to establish a connection between my server code, written in nodejs using the expressjs framework, and my database which is built on orientdb. Initially, I aimed to store sessions in the database but encountered difficulties when trying to ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

The default selection in res.format is not being properly recognized

When I make a request with the accept header set as "application/json, text/javascript, */*; q=0.01", the response is always in HTML format instead of the default format specified. It seems like something is missing here. Given that the header does not spe ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Using functions as properties in React.js

I am facing an issue while trying to pass a function as a prop. Although I have done this successfully in the past, now I am getting an error (this.props.functionName is not a function). I have a child component called Navbar and a parent component named ...

Mongoose: CastError occurs when querying with an incorrect ObjectId for a nested object

I have the following schema defined: var Topic = new Schema({ text: String, topicId: String, comments: [{type: Schema.Types.ObjectId, ref:'Comment'}] }); var Comment = new Schema({ text: String }); I am working on a RESTFul API that w ...

Struggling to save a signature created with an HTML5 Canvas to the database

I've been on the hunt for a reliable signature capture script that can save signatures to MySQL, and I finally found one that fits the bill. However, there are two issues that need addressing: The canvas doesn't clear the signature when the c ...

Using regular expressions to identify the presence of "&", parentheses, and consecutive letters in a string

I specialize in working with JavaScript and I have a need to verify if my text contains certain characters. Specifically, I want to check for the presence of parentheses (), ampersands (&), and repeating letters within the text. Here are some examples: te ...

From vanilla JavaScript to the powerful lodash library

Can you help me determine if these statements are equivalent? myApp.filter('myFilter', function() { var result, i, sport, y, contains, league; return function(sports, filterBy) { if (angular.isUndefined(sports) || !filterBy) { ...

Can web code be integrated locally while developing hybrid apps with native languages?

My friends and I are currently working on developing an app for both iOS and Android using native language. We are hoping to incorporate one or two angular/ionic pages into our project. I have created some ionic pages that can be accessed by the native l ...

Sending arguments from an NPM script to a NodeJS script

In my main script (publish-all.js), I am trying to call the npm publish script of an Angular project. This Angular project also has a sub-script (publish.js) that performs various tasks (creating folders, copying files, moving folders...) after running ng ...

Adding new data to an object of objects can be a complex task, especially when the new data is coming from a state variable in React that is also an

I'm currently working on populating an object of objects with new data that is being stored in a state variable in React, which is also an object. Here's the code snippet I have: let userData = { harsh:{ password:"harsh", ema ...

Identifying the completion of loading a HTML page using an object tag

I am trying to load an HTML page using an object tag, and once the page is fully downloaded, I want to display something. I have attempted the following approach, but it is not working: document.querySelector(".obj_excel").addEventListener("load", funct ...

The Shopify Pixel Extension has encountered an issue - error code 1

Looking to develop a web pixel extension for my Shopify app, I followed the official guide: While building the app, encountered this error: extensions | my-app-pixel (C:\projects\shopify\my-app-pixel\node_modules\.bin\shopify ...

Retrieve the modal ID when the anchor tag is clicked in order to open the modal using PHP

I am facing an issue with opening a modal and passing the id value using JavaScript. The id value is shown in a hidden input field. <a href="#modal2" data-toggle="modal" data-id="<?php echo $CRow['id'];?>" id="<?php echo $CRow[& ...

Creating an AngularJS service or factory that dynamically compiles HTML using a variable from the $scope

Looking to streamline a commonly used function in various controllers within an AngularJS project by creating a service/factory that can be accessed through $rootScope. The objective is to refactor the existing function: $scope.twitterRefresh = function(o ...