Unexpected behavior with ng-show binding

I am currently working on implementing a toggle feature in my form. The idea is that when I click one button, it should display a section with the corresponding name, and hide the other sections. However, I am facing an issue related to scope. When I do not use an isolated scope for my substeps, both substeps appear active or inactive together, which is not the desired behavior. On the other hand, if I implement an isolated scope, the isActive() function is never called.

Here is the code snippet:

<div ng-controller='SubstepCtrl'>
    <button activates='CreateNewMeter'>
        Create new Meter
    </button>

    <button activates='UseExistingMeter'>
        Use Existing Meter
    </button>

    <div class='sub-step' substep='CreateNewMeter' ng-show='isActive(name)'>
        <h1>Create New Meter</h1>
    </div>

    <div class='sub-step' substep='UseExistingMeter' ng-show='isActive(name)'>
        <h1>Use Existing Meter</h1>
    </div>
</div>

In Angular:

.controller('SubstepCtrl', function($scope) {
    $scope.activeSubstepName = undefined;
    $scope.isActive = function(name) {
        return $scope.activeSubstepName == name;
    };
})

.directive('activates', function() {
    return {
        link: function($scope, $element, $attrs) {
            $element.on('click', function() {
                $scope.activeSubstepName = $attrs.activates;
                $scope.$apply();
            });
        }
    };
})

.directive('substep', function() {
    return {
        link: function($scope, $element, $attrs) {
            $scope.name = $attrs.substep;
        }
    };
});

I have found a workaround using JQuery, but I would prefer an Angular solution. Is there a way to achieve this using Angular?

The intended behavior is that clicking "Create new Meter" should display the "CreateNewMeter" substep while hiding "UseExistingMeter". It seems that the issue lies in the substep divs not creating a separate scope and instead using the parent scope, resulting in 'name' being undefined - is that correct?

If so, how can this be resolved?

Answer №1

One approach is to develop a unique directive with its own independent scope. This method offers more flexibility, making it possible to include multiple sub-steps as needed.

When configuring the isolate scope within the directive, ensure that you define properties for both the name and the isActive function. The name can be set as an @ attribute in the directive's scope, representing the string specified in the HTML. Additionally, create a function named showWhen (passed to the directive using the & syntax), which requires an object encapsulating the specified name parameter within your directive.

Example HTML structure:


<div ng-controller='SubstepCtrl'>
    <button activates='CreateNewMeter'>
        Create new Meter
    </button>

    <button activates='UseExistingMeter'>
        Use Existing Meter
    </button>

    <button activates='UseImaginaryMeter'>
        Use Imaginary Meter
    </button>

    <button activates='none'>
        "Clear" all
    </button>

    <substep name="CreateNewMeter" show-when="isActive(name)">
      <h1>Create New Meter</h1>
    </substep>

    <substep name="UseExistingMeter" show-when="isActive(name)">
      <h1>Use Existing Meter</h1>
    </substep>

    <substep name="UseImaginaryMeter" show-when="isActive(name)">
      <h1>Use Imaginary Meter</h1>
    </substep>
</div>

Directive implementation:

.directive('substep', function() {
    return {
      restrict: 'E',
      scope: {
        name: '@',
        showWhen: '&'
      },
      transclude: true,
      template: '<div ng-transclude class="sub-step" ng-show="showWhen({name:name})"></div>'
    };
});

Explore this working example on Plunker: http://plnkr.co/edit/TKJehABKIPPHRbrUrqr3?p=preview

Answer №2

Give this a try, eliminating the need for creating your own directive:

<div ng-controller='SubstepCtrl'>
    <button ng-click='setMeter("new")'>
        Create a new Meter
    </button>

    <button activates='setMeter("existing")'>
        Use an Existing Meter
    </button>

    <div class='sub-step' substep='CreateNewMeter' ng-show='meter === "new"'>
        <h1>Creating a New Meter</h1>
    </div>

    <div class='sub-step' substep='UseExistingMeter' ng-show='meter === "existing"'>
        <h1>Using an Existing Meter</h1>
    </div>
</div>

Set up a function on your controllers' scope:

.controller('SubstepCtrl', function($scope) {
    $scope.activeSubstepName = undefined;
    $scope.isActive = function(name) {
        return $scope.activeSubstepName == name;
    };
    $scope.meter = null;
    $scope.setMeter = function(meterType) {
        $scope.meter = meterType;
    };
});

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

JQuery Autocomplete Error: Unable to access property 'value' of undefined

I am currently utilizing a jquery autocomplete plugin found here. However, I am encountering an issue when I click on a filtered result, triggering the following error: Uncaught TypeError: Cannot read property 'value' of undefined Upon inspecti ...

What is the most effective way to transmit multiple pieces of server-side data to JavaScript?

Imagine having multiple Javascript codes embedded in pages. Currently, it's simple to initialize variables by using Print/Echo statements to set JavaScript values. For example: var x = <?php echo('This is a value');?> Initially, I co ...

jQuery tipsy not triggering click event in Internet Explorer

Hey there! I've been using the jquery tipsy plugin for displaying colour names above colour swatch images. One thing I'm trying to do is trigger a checkbox to be checked/unchecked when a user clicks on the image. $(document).ready(function(){ ...

AngularJS allow you to make interval calls with parameters

How can I use the $interval function to call another function with a parameter? $interval(getRecordEveryTime(2), 100000); function getRecordEveryTime(contactId) { console.log(contactId + ' timer running'); } ...

When running the PHP script, the output is shown in the console rather than in the

Here is a PHP script snippet that I am working with: <?php add_action('wp_ajax_nopriv_getuser', 'getuser'); add_action('wp_ajax_getuser', 'getuser'); function getuser($str) { global $wpdb; if(!wp_verif ...

Increase the lag time for the execution of the on('data') function in Node.js

In my current function, it searches data from a database and performs an action with it. For the purpose of this demonstration, it simply increments a counter. exports.fullThreads = function(){ return new Promise((resolve, reject) => { MongoClien ...

Unspecified error with Laravel request

Currently, I am a novice in Laravel and still in the process of exploring everything. I have been using Angular HTTP post to transfer data to Laravel, and in the Laravel controller, I have successfully used dd($request) to debug the request object: dd($re ...

Error: The configuration object is invalid, and I am unable to deploy my server to test the bundled code

After running the webpack --mode production command to build the dist folder, I encountered an error when trying to run the server as the app is still running in developer mode. The error message displayed was: C:\Users\Bymet\Documents&bs ...

Tips on calculating the combined value of price and quantity simultaneously

Greetings, kindly bear with me as my knowledge of JS scripting is quite limited. My expertise lies more in PHP programming. I stumbled upon this neat and straightforward script that calculates the total of product table rows and also provides the grand t ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

Learn how to retrieve data prior to rendering with Vue 3 and the composition api

Is there a way to fetch data from an API and populate my store (such as user info) before the entire page and components load? I have been struggling to find a solution. I recently came across the beforeRouteEnter method that can be used with the options ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

The preventDefault() function is not functioning properly on the <a> tag

As a JavaScript beginner, I decided to create an accordion menu using JavaScript. Although I was successful in implementing it, I encountered a bug in my program. In this scenario, uppercase letters represent first-level menus while lowercase letters repr ...

Customize the top bar text in your Zurb Foundation for Apps App based on the current page

Currently, my project involves the creation of a single page application utilizing Zurb's Foundation for Applications and Angular. Can anyone suggest an optimal method to showcase different text in the top bar (nav bar) depending on the current route ...

Is it possible to stack one Canvas on top of another?

Right now, I am engaged in a process that involves: creating a canvas and attaching it to a division applying a background image through CSS to that canvas. drawing a hex grid on the canvas placing PNGs on the canvas. animating those PNGs to show "movem ...

Whenever the click event is triggered, Ajax is making numerous duplicate calls

Each time I click to fetch my content using an AJAX call, the calls end up duplicating themselves. I've tried various on-click events I came across on Stackoverflow threads, but unfortunately none of them seem to be solving the issue. $(document).rea ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

Prevent clicking on a specific column in a table using Jquery

Attempting to utilize Jquery for clicking on a table row in order to navigate to a new page. However, encountering an issue with the last column containing a button that redirects to a new page when clicked on the edge. Is there a way to disable the oncl ...

What is the importance of cloning React state before making changes or while working on it?

Someone advised me to always create a clone or copy of the react state before making any changes to it. const newState = [...this.state] newState.name = 'hardik' I'm still unsure about the reason behind this recommendation. Why shouldn&apos ...

Send data using only Javascript

Hey there, I'm a beginner in javascript and I'm having some trouble submitting a form using pure javascript. Here is my code: var myform = document.getElementById('js-post-form'); myform.addEventListener('submit', function(e ...