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

In the process of creating my initial discord bot, struggling to incorporate advanced functionalities beyond basic commands

I am currently using discord.js and JavaScript to code. I have created a test bot and followed step-by-step guides meticulously, but the bot only responds to basic "ping pong" commands. Whenever I try to add more complex commands, the bot stops functioning ...

Can you explain the distinction between using call and apply?

Can you explain the distinction between utilizing Function.prototype.apply() and Function.prototype.call() to execute a function? const func = function() { alert("Hello world!"); }; func.apply() compared to func.call() Do performance dispar ...

AngularJS Code is displayed upon page refresh or loading

Just starting out with AngularJS. Currently working on retrieving data from a Rest API and displaying it on the page. Here is the code snippet I am using: $http.get(local_url+'/data'). then(function(response) { $scope.data = respon ...

What are some effective methods for locating dual edges within a Half-Edge (DCEL) data structure?

I have implemented a HalfEdge data structure to represent the connectivity between faces in my mesh. While importing an external model, I construct the HalfEdge structure. However, for meshes with numerous triangles, the construction process is time-consu ...

Converting JSON data into an array of a particular type in Angular

My current challenge involves converting JSON data into an array of Recipe objects. Here is the response retrieved from the API: { "criteria": { "requirePictures": true, "q": null, "allowedIngredient": null, "excluded ...

The dropdown menu adjusts its value based on the selected radio button

When I select the "12 hour" radio button, the drop-down values change to 1 am - 12 am and 1 pm - 12 pm. If I select 24 hours, then the values change to 1-24. Below is my code: <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script> ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

What are the steps for initializing a session in Vue.js with Django upon a successful login?

Upon successful login, I want to redirect to a page indicating success and also include a session. How can this be achieved? I am using HTML with Vue.js for the front end and Django for the back end. Below is my Vue.js script for the login: <script> ...

stop all HTML5 videos when a specific video is played using jQuery

I am facing an issue with 10 HTML5 videos on the same page, CHALLENGE Whenever I click on different videos, they all start playing simultaneously... <div><video class="SetVideo"></video><button class="videoP"></button>< ...

Generating random indexes for the Answer button to render

How can we ensure that the correct button within the Question component is not always rendered first among the mapped incorrect buttons for each question? Is there a way to randomize the positions of both correct and incorrect answers when displaying them, ...

Methods to troubleshoot problem of angular component loading issue in firefox with ViewEncapsulation.Native

I am encountering a problem with loading an angular component using ViewEncapsulation.Native in firefox, edge, and ipad chrome. Interestingly, there is no issue on safari on mac, chrome on windows, or chrome on android. Error: hostEl.createShadowRoot is ...

How can I terminate a parent function in NodeJS when inside a virtual function?

Here is something similar to the code snippet below: var async = require(async) function start () { async.series( [ function (callback) { // do something callback(null, "Done doing something") ...

I need help getting my Vue.JS project to function properly when it is deployed on a server

After creating a new VueJS project using the Vue UI, I noticed that everything runs smoothly locally at http://localhost:8080/ with no errors. However, when I build the project and upload the files from the dist folder to my hosting package via FTP, I end ...

Convert a boolean value to a string using filter in AngularJS

I am working on an AngularJS app and need to create a filter. In my database, I have a string value that indicates whether the data is active or inactive. I use 'S' for active and 'N' for inactive. I added a checkbox button on my page t ...

How to modify this to return a function and eliminate the need for declaring a function

Greetings! I understand that this may seem simple to some of you, but I am feeling quite lost. I've been tasked with removing the function declaration and converting it into a return function. Any assistance would be greatly appreciated. const canView ...

Exploring the nesting of client components in Next.jsIf you are

Exploring the realm of NextJS and React, I find myself delving into the realm of client components. One such client component I'm working with is called Form.jsx. It looks something like this: export default function FormHome() { ... a plethora of ...

How can Angular hide a global component when a particular route is accessed?

Is it possible to hide a global component in Angular when a specific route is opened? For instance, consider the following code: app.component.html <app-header></app-header> <app-banner></app-banner> <!-- Global Component I w ...

AngularJS Resource does not support array as input

I am struggling with AngularJS to fetch a JSON array (a list of strings). I have set up a Resource for this purpose as shown below: packageResource.factory('Package', ['$resource', function($resource) { return $resource('/stat ...

An issue arose during the installation of nodemon and jest, about errors with versions and a pes

Currently, I am facing an issue while trying to set up jest and nodemon for my nodejs project. My development environment includes vscode, npm version 6.13.7, and node version 13.8.0. Whenever I try to install nodemon via the command line, the console disp ...

Bringing Back User Permissions to an AngularJS Application from ASP.NET Identity via OAuth and Bearer Tokens

I am currently in the process of developing an AngularJS Single Page Application with a backend running as a WebAPI that originated from a Visual Studio 2013 template. AngularJS handles all functionalities, including login, and I have successfully configur ...