Ways to continuously refresh the display in AngularJS

There are 2 div elements below, and I need to display only one of them depending on whether the doStuff() function is triggered in the controller when a specific anchor element is clicked.

<div ng-controller='myController'>
    <div ng-show="{{states['currentState'] == 'A'}}">
        // This div will be displayed if currentState is A
        <a ng-click="doStuff('B')">Do stuff and show B</a>
    </div>
    <div ng-show="{{states['currentState'] == 'B'}}">
        // This div will be displayed if currentState is B
    </div>
</div>

Here is the code for the controller:

myApp.controller('myController', ['$scope', function($scope) {

  var states = ['A', 'B'];
  $scope.states = states;
  $scope.states['currentState'] = $scope.states['currentState'] || 'A';

  $scope.doStuff = function(stateToShow) {
    // Perform actions here
    $scope.states['currentState'] = stateToShow;
  };

}]);

The above code does not switch to state 'B' after clicking the Do stuff and show B anchor element. Can anyone help me understand why?

Edit

app.js

 //...

    .state('home', {
        url: '/',
        views: {

            '': { templateUrl: 'partials/index.html' },

            'myView@home': {
                templateUrl: 'partials/myView.html',
                controller: 'VehicleController'
            }
            // Other named ui views
        }

    })

 //...  

index.html

<div class="main">
    <div class="container">
        <div class="row margin-bottom-40">
            <div class="col-md-12 col-sm-12">
                <div class="content-page">
                    <div class="row">
                        <div ui-view="myView"></div>
                        <!-- other named ui-views -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

myView.html

<div ng-controller='myController'>
    <div ng-show="states['currentState'] == 'A'">
        // This div gets shown if currentState is A
        <a ng-click="doStuff('B')">Do stuff and show B</a>
    </div>
    <div ng-show="states['currentState'] == 'B'">
        // This div gets shown if currentState is B
    </div>
</div>

Answer №1

Updating the scope is in progress. The issue might lie with the ng-show directive where you are using "{{notation}}" as a string, which always evaluates to truthy (even if it contains "true" or "false"). It's advisable to use the expression directly.

Modify

 <div ng-show="{{states['currentState'] == 'A'}}">

to

 <div ng-show="states.currentState === 'A'">

View Demo

Referencing the Documentation:-

According to the ngShow expression, if the expression evaluates to true, the element is displayed; else it is hidden.

Answer №2

You are on the right track. The issue with your code not working is because the "ng-show" attribute does not require the "{{" and "}}" symbols to function properly.

I tested your code without those symbols, and it now functions as you originally intended.

<div ng-show="states['currentState'] == 'A'">
    // This div is displayed when currentState is A
    <a ng-click="doStuff('B')">Do something and show B</a>
</div>
<div ng-show="states['currentState'] == 'B'">
    // This div is displayed when currentState is B
</div>

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

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

Verify whether a document retrieved from mongoDB contains a certain property

Dealing with user accounts in Mongoose, I have set it up so that the user can use their phone number to sign in: const account = await db.Account.findOne({ phone: req.body.phone }) : Now, I need to confirm if there is a property named verified in the acco ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

Is it possible to replicate the functionality of "npm run x" without including a "scripts" entry?

If you want to run a node command within the "context" of your installed node_modules, one way to do it is by adding an entry in the scripts field of your package.json. For example: ... "scripts": { "test": "mocha --recursive test/**/*.js --compiler ...

Ways to retrieve and contrast the border style of an image utilizing javascript

I'm currently attempting to identify images on my webpage that have the style border: 1px #c6c6c6 solid; let images = document.getElementsByTagName('img'); for (let i = 0; i < images.length; i++) { if (images[i].style.border === "1px ...

Is there a way to display the button just once in a map function while still retaining access to the iteration value?

Utilizing formik within material-ui for a form has been quite productive. I've implemented a map function to print text fields and managed to display the Submit button only once by targeting the index. However, there's an issue when attempting to ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

Utilize the setInterval method to repeatedly call the random function

Can someone assist me in setting a time interval of about 1 second for this function? function random_imglink(){ var myimages=new Array() //insert your desired random images below myimages[1]="/documents/templates/bilgiteknolojileri/standalo ...

"Utilize the power of parent checkboxes in AngularJS to effortlessly toggle the selection status

Looking to toggle the selection of child check boxes depending on parent check boxes, specifically in AngularJS. Would appreciate any help with a solution. This is what I'm aiming for: ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

When I attempted to use jQuery to access the innerHTML of list items, I encountered the issue of it returning as Undefined

For my grocery list application created with Angular 4, I need the user to click on an item and have it added to the bookmarked section. Despite using jQuery to access the innerHTML of the li when hovered over, the value keeps returning as "undefined." In ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Issues with jQuery autocomplete functionality on certain elements are not uncommon

I've been experimenting with creating a user script for Opera using Greasemonkey to implement autocomplete functionality on input elements within web pages. However, I've encountered some issues with the script not working as expected. Initially ...

Can the warning about a missing dependency in useEffect be incorrect at times?

After using hooks for some time, I still don't quite grasp why React insists on including certain dependencies in my useEffect that I don't want. My understanding of the 'dependencies' in a useEffect hook is as follows: You should add ...

Show the dropdown menu with names from the array in the ajax response

<html> <select name="cars"> <option value="34">Volvo XC90</option> <option value="54">Saab 95</option> <option value="12">Mercedes SLK</option> <option value="10">Audi TT</option> </select> ...

Combining the Powers of ExpressJS and MeteorJS

I am currently using an Epress JS rest api to send data to a MongoDB database. I'm curious if it's feasible to incorporate Meteor JS for fetching these values from the MongoDB. Any insights or suggestions would be greatly valued. Thank you ...

Securing your Node.js connect-rest REST API with OAuth: A comprehensive guide

After conducting an extensive search on Google for examples related to my query, I was left empty-handed due to the generic name of the "connect-rest" package. My objective is to secure a server side API that I have built using the Node module "connect-re ...

AngularJS Data table: unresponsive feature not functioning

I'm currently utilizing the angular-datatables plugin along with the responsive table feature, but unfortunately it's not functioning as expected: the table appears without the responsive design. Module: (function () { 'use strict&apos ...

What are the necessary conditions for executing npm start?

I'm encountering issues running npm start in my project, which is linked to my package.json file below: { "name": "babek", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test speci ...