Issue with custom directive - bi-directional binding not functioning as expected

I'm currently working on creating a custom directive in Angular that transforms a tag into a toggle button, similar to a checkbox. As of now, the code I've developed updates the internal variable within isolated scope, but bidirectional binding doesn't seem to be functioning properly. Although clicking the button triggers the toggling effect (the CSS class is being added and removed), the value of myVariable isn't being updated.

Any assistance would be greatly appreciated!

How to Use:

<button toggle-button="myVariable">My Button</button>

Directive Implementation:

(function() {

var directive = function () {

    return {

        restrict: 'A',

        scope: {
            toggleButton: '=checked'
        },

        link: function($scope, element, attrs) {

            $scope.$watch('checked', function(newVal, oldVal) {
                newVal ? element.addClass ('on') : element.removeClass('on');
            });

            element.bind('click', function() {
                $scope.checked = !$scope.checked;
                $scope.$apply();
            });
        }
    };
};

angular.module('myApp')
    .directive('toggleButton', directive );

}());

Answer №1

simply substitute

scope: {
            toggleButton: '=checked'
        }

with

 scope: {
            checked: '=toggleButton'
        }

Answer №2

It appears that your directive scope is searching for a non-existent attribute.

Consider revising:

 scope: {
     toggleButton: '=checked'
  },

To this:

scope: {
    toggleButton: '='
},

The key difference is that =checked attempts to find the attribute checked, while = utilizes the same attribute as the property name in the scope object.

You may also need to adjust the $watch, but alternatively, consider using ng-class.

Answer №3

As mentioned by charlietfl, the checked variable is unnecessary in this case. The changes should be made to the external variable instead.

Here is an improved version of the code:

angular.module('components', [])
    .directive('toggleButton', function () {
        return {
            restrict: 'A',
            scope:{
                toggleButton:'='
            },
            link: function($scope, $element, $attrs) {    
                $scope.$watch('toggleButton', function(newVal) {
                    newVal ? $element.addClass ('on') : $element.removeClass('on');
                });
                $element.bind('click', function() {
                    $scope.toggleButton = !$scope.toggleButton;
                    $scope.$apply();
                });
            }

        }
    })

angular.module('HelloApp', ['components'])

View the updated code on jsFiddle

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

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...

Having difficulty importing SVG files into the canvas

I'm encountering difficulties when attempting to import SVGs to the canvas and use setZoom() with FabricJS. I am currently working with version "2.0.0.rc4". I have made attempts to import them using two different methods, each with its own set of cha ...

Display only one field and hide the other field using a jQuery IF/ELSE statement

Hey there! I have a situation where I need to toggle between two fields - one is a text field and the other is a text_area field. When a user clicks on one field, the other should be hidden and vice versa. I've tried using JQuery for this: $(document ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

Basic example of jQuery in an ASPX file

I can't figure out why this basic example is not working. In my WebApplication, I have a script: function myAlert() { $("#Button1").click(function () { alert("Hello world!"); }); } In my asp page, I have the following code: < ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Guide on concatenating the output values using jQuery

After selecting the matched records from the database, I returned to the previous page. Although I retrieved all the values, I am unsure how to append these return values on this page. What I need is to replace ROOM 2, Room 3... with the value in value.roo ...

Use JavaScript to change the CSS pseudo-class from :hover to :active for touch devices

Looking to eliminate hover effects on touch devices? While it's recommended to use a hover class for hover effects, instead of the hover pseudo-class, for easier removal later on, it can be a challenge if your site is already coded. However, there&apo ...

Provide input data to the function for delivery purposes

Creating a simple webpage with a form input that triggers a script to request JSON data from the server based on the user's input. The challenge is passing the value from the input field to a function for processing. var search = document.querySele ...

Position the previous and next buttons next to the thumbnail images

I've implemented the cycle2 jQuery plugin on my website successfully, but I'm facing an issue with positioning the prev and next buttons next to my thumbnails. I want them to be aligned with the first and last thumbnail without relying on absolut ...

Trouble with translating code from JavaScript to Python due to hash algorithm discrepancy

In an attempt to achieve consistent hash function results between JavaScript and Python, I encountered a roadblock when trying to convert my JavaScript function to its Python equivalent, resulting in unexpected outcomes. Original JavaScript Function: func ...

Passing model data using MVC and ajax

I'm encountering an issue while attempting to send data back to my save method using ajax. I prefer this method because it allows me to reuse the form on multiple screens by rendering it as a partial page with the same save function. The problem I&ap ...

A guide to sorting an object with integer keys by its values using JavaScript

I am facing an issue with sorting a map by values instead of keys. No matter what I do, it always ends up getting sorted by the keys. On the server side, I have a map that is already sorted. When I send this map to JavaScript using JSON, it gets re-ordere ...

React: Implementing Material-UI Typography with custom inline spacing

Take a look at this code snippet: <Typography className={classes.welcomeMessage} variant="h1"> A <span className={classes.redText}>smart nation </span> approach to <span className={classes.redText} ...

Using a Vue.js component in a Laravel Blade template can be achieved by first registering the component

I added a component registration in my app.js as shown below: Vue.component('navbar', require('./components/Navbar.vue')); Now I am looking to import that component into my blade.php file like so: <template> <nav class="navb ...

Send the appropriate data once the response has been completed

My Express.JS server has multiple res.json responses. In order to conduct statistics, logging, and debugging, I am looking to capture the response payload using a universal hook. While I have come across the finish event res.on('finish'), I am s ...

Utilizing JavaScript and the Document Object Model (DOM) to display images within a

My main goal is to have images load dynamically as the background of the browser frame, without any white spaces or repeats. I've successfully achieved this statically, but now I want to implement it so that different images are generated randomly. W ...

Having issues with custom directives not functioning properly within AngularJS' RouteProvider

Currently, I'm in the process of learning AngularJS and specifically focusing on the route provider feature. I have successfully built a few pages that functioned well independently. Now, my aim is to implement the route provider into my project. In m ...

Is there a way to track and monitor the ngRoute requests that are being made?

I am in the process of transferring a fairly large Angular 1.6 application from an old build system to Yarn/Webpack. Our routing is based on ngRoute with a complex promise chain. While sorting out the imports and dependencies, I keep encountering this err ...

In Angular's production build on Webkit/Safari, the left-hand side of the operator '=' must be a reference

Recently, I completed a project using Angular. After successfully building it for production without any errors, everything seemed to work perfectly on Chrome. However, when attempting to run the app on Webkit/Safari, an error was displayed in the cons ...