Comparing global variables in ng-switch: Best practices

I'm currently utilizing the AngularJS $rootScope object to expose some global constants that should be accessible to both controllers and views:

var app = angular.module('myApp', []);

app.run(function ($rootScope) {
    $rootScope.myConstant = 2;
});

Rendering a global value in a view works correctly:

{{myConstant}}

Similarly, referencing the global value in an ng-if condition also functions properly:

<span ng-if="someValue == myConstant">Conditional content</span>.

However, when trying to use the same value for comparison within an ng-switch block, it never seems to evaluate to true. Check out this JSFiddle for a demonstration of my attempt to make this work. I have experimented with explicitly referencing the constant value as a member of $rootScope and as an expression (inside double curly braces), but nothing seems to work.

Any insights into what I might be doing incorrectly?

Thank you,

Tim

Answer №1

To avoid using ng-switch-when, you have the option to modify the expression in ng-switch-on to generate a specific value when myConstant is equal to item.value:

<span ng-switch on="{true:'const', false: item.value}[myConstant == item.value]">
    <span ng-switch-when="const">
        <span class="blue">{{item.name}}</span> (highlighted by ng-switch) 
    </span>
    <span ng-switch-when="4">
        <span class="red">{{item.name}}</span> (highlighted by ng-switch) 
    </span>
    <span ng-switch-default>
        {{item.name}}
    </span>
</span>

See it in action here.

Answer №2

If you're feeling adventurous, why not create your own solution? :)

(I can't guarantee its efficiency and it hasn't been extensively tested since I just put it together)

Check out this JSFiddle for a demo

app.directive('customSwitch', function () {
    return {
        controller: function ($scope) {
            var _value;
            this.getValue = function () {
                return _value;
            };
            this.setValue = function (value) {
                _value = value;
            };

            var _whensCount = 0;
            this.addWhen = function (value) {
                _whensCount++;
            }
            this.removeWhen = function (value) {
                _whensCount--;
            }
            this.hasWhens = function () {
                return _whensCount < -1;
            };
        },
        link: function (scope, element, attrs, controller) {
            scope.$watch(function () {
                return scope.$eval(attrs.customSwitchOn);
            }, function (value) {
                controller.setValue(value);
            });
        }
    };   
});

app.directive('customSwitchWhen', function () {
    return {
        require: '^customSwitch',
        template: '<span ng-transclude></span>',
        transclude: true,
        replace: true,
        link: function (scope, element, attrs, controller) {
            scope.$watch(function () {
                return controller.getValue() === scope.$eval(attrs.customSwitchWhen);
            }, function (value) {
                if (value) {
                    controller.addWhen();           
                } else { 
                    controller.removeWhen();      
                }
                element.attr('style', value ? '' : 'display:none;');
            });
        }
    };   
});

app.directive('customSwitchDefault', function () {
    return {
        require: '^customSwitch',
        template: '<span ng-transclude></span>',
        transclude: true,
        replace: true,
        link: function (scope, element, attrs, controller) {
            scope.$watch(controller.hasWhens, function (value) {
                element.attr('style', value ? '' : 'display:none;');
            });
        }
    };   
});

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

A JavaScript pop-up box with two windows

Struggling to create two separate dialog boxes using this code. The issue is that when I add the code for the second dialog box, it only appears if the first one does too. Here's the code for the first dialog: function showPopUp(el) { var ...

organizing various kinds of data values within an array

Within this array, I have two types of variables - an integer and a string. My goal is to sort the array either alphabetically or by the length of the string. However, it seems that the sorting algorithm is prioritizing the integer over the string. ...

Executing a jQuery function automatically & Invoking a jQuery function using the onClick attribute in an HTML element

Having some issues with jQuery and could use some assistance... Currently, I am trying to have a jQuery function automatically execute when the page loads, as well as when a button is clicked. [Previous Issue] Previously, the jQuery function would automa ...

Using jquery to dynamically retrieve the unique property identifier

I have a dynamically generated table with a button labeled as view images. Each time this button is clicked, I need to retrieve the image names from the database for that specific property. <?php foreach($unapproved as $unapp):?> < ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Validation of the email address continually fails

I tried using a validation method that I found in various StackOverflow answers, but for some reason, the email always comes up as invalid. Because of this, the second condition is never being executed. Can someone point out what I might be misunderstand ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

Are there any other options besides using the React Material-UI makeStyles() function for styling class Components?

While experimenting with the makeStyles() function in Material-UI's React library, I encountered a specific error message: The use of hooks is limited to the body of a function component. Below is a snippet of the code that triggered this error: ...

Ways to sum up the values within a JSON object

Currently, I am using an AJAX call to fetch JSON data from an API. My goal now is to add up all the visits. This is what I have implemented so far. Any suggestions on how I can achieve that? $(document).ready(function() { var X = []; var Y = []; var d ...

Moving specified data from one interactive table to another interactive table

In my setup, there are two tables - one for products and another for customers: <table cellpadding="0" cellspacing="0"> <thead> <tr> <th>Product Code</th> </tr> </thead> ...

JavaScript ECMAScript 6 - WARNING: "Decorators can only be applied to a class when exporting"

In ECMAScript 6, I am attempting to export a function so that I can import it and utilize it in other files for the sake of writing DRY code. However, an error message is appearing: You can only use decorators on an export when exporting a class (16:0) ...

Having trouble with the Moment.js diff function in your React Native project?

Within my React Native application, I have implemented Moment.js and included the following code snippet: const expDate = moment(new Date(val)).format('MM-DD-YYYY'); const nowDate = moment().format('MM-DD-YYYY'); const diff = nowDate.d ...

Refresh the Angular ion-view from a different controller

Greetings to all fellow developers on stackoverflow! I am a newbie here and just starting out with AngularJS. My current project involves building an Ionic app, but I am encountering an issue that I need assistance with. The goal is to update the date di ...

React App with Material UI V1-beta Integration

I just installed the Create React App example from Material-UI.com. curl https://codeload.github.com/callemall/material-ui/tar.gz/v1-beta | tar -xz --strip=2 material-ui-1-beta/examples/create-react-app Upon installation, I encountered the following erro ...

"The interplay of Vue components: exploring the relationships, lifecycle hooks

Brand new to utilizing Vue.js. I am exploring the concept of having a single parent component and two child components that need to communicate asynchronously through Vue's event bus system. This involves using a dummy Vue object as a shared container ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

How to eliminate the unnecessary gap between rows in a Vue div displayed as a grid

I have recently started working with Vue and in my current project, I encountered a challenge where I needed to display 2 players in each row within a div. To achieve this, I utilized the display: grid; CSS property on the playerDiv id. However, I am facin ...

Exploring the Magic of Class Variable Destructuring in React

Is there a simpler method to break down a prop object and assign them to variables of the same name in the class? I am familiar with ({ first: this.first, second: this.second, } = props) however, it can get complicated when dealing with numerous variable ...

Having trouble triggering the onclick event on a dynamically created table using JavaScript

I am facing an issue with adding a table programmatically that has an onclick event triggering a specific JavaScript function using the row's id for editing purposes. Unfortunately, the function is not being called as expected. I have attempted to mod ...