Checkbox within label fails to trigger ng-change event

Here is an example of my HTML code:

<input ng-controller="cboxCtrl" type="checkbox" 
       ng-model="hideCompleted" ng-change="hideChanged()"/>

Here is the corresponding controller code:

angular.module('simple-todos').controller('cboxCtrl', ['$scope',  
function ($scope) {
    console.log("starting");

    $scope.hideChanged = function () {
        console.log("in hideChanged() ");
    };
}]); // end controller

Everything works well and I can see the message on the console when I click the checkbox. However, if I wrap the checkbox with a label:

<label>
    <input ng-controller="cboxCtrl" type="checkbox" 
           ng-model="hideCompleted" ng-change="hideChanged()"/>
    Some text to explain the checkbox
</label>

The ng-change function does not get triggered when I click the checkbox. It seems like a scoping issue, but I'm unsure what exactly is causing it. When I replace labels with divs (even though it affects the layout), the ng-change function works as expected.

Answer №1

My jsfiddle has been created using your code and it seems to be functioning correctly.

Here is the link to the jsfiddle.

angular.module('simple-todos', []).controller('cboxCtrl', ['$scope', cboxCtrl]);


function cboxCtrl($scope) {
  console.log("starting");

  $scope.hideChanged = function() {
    console.log("in hideChanged()");
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="simple-todos">
  <label>
    <input ng-controller="cboxCtrl" type="checkbox" ng-model="hideCompleted" ng-change="hideChanged()" />some text for the label
  </label>
</div>

Would you be willing to share the entirety of your code?

Answer №2

By clicking on the label, you can also activate the ng-change event. Whether it's a checkbox or radio button, simply clicking on the label should trigger the assigned function within the scope.

Answer №3

Before running this code, make sure to verify the compatibility with your current browser and try testing it on other browsers as well. AngularJS does not provide support for IE8 or any earlier versions anymore. For more information, visit this link: https://docs.angularjs.org/guide/ie

Answer №4

It is important to transfer your ng-change from the checkbox to the ng-click of the enclosing label

<label ng-click="hideChanged()">
    <input ng-controller="cboxCtrl" type="checkbox" ng-model="hideCompleted" />
    Some text describing the checkbox
</label>

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

Capture the contents of a table cell and store it in the clipboard

Is there a way to create a hover copy button in a table cell without actually placing the button inside the <td> tags? The goal is to allow users to easily copy text from a specific column cell by hovering over it. function myFunction() { var c ...

Including files in node package without specifying the name of the dist directory

In my library directory structure for seamless import by node js projects, it looks like this: my-lib/ ├─ dist/ │ ├─ index.js │ ├─ foo.js ├─ src/ │ ├─ index.ts │ ├─ foo.ts ├─ package.json Take a look at my package.j ...

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

EJS include function not working properly

In most cases, my EJS pages include the code below: <%- include('elements/fbviewpagepixel.ejs') %> Everything runs smoothly except for one particular page where I encountered an error message stating include is not a function. I managed t ...

Can you determine if a function is a generator function if .bind() has already been applied to it?

It seems like using .bind(this) on a generator function is interfering with determining if the function is actually a generator. Any suggestions on how to resolve this issue? function checkIfGenerator(fn) { if(!fn) { return false; } ...

When arriving on a page via an HTML anchor tag, the CSS style does not appear. How can I "reinstate" it?

I have set up a website with an index.html page that links to a contact.html page using anchor tags. On the contact.html page, there are anchor tags that should navigate the user back to specific sections of the index.html page. The navigation works fine, ...

Is it possible to determine the time format preference of the user's device in Angular? For example, whether they use a 24-hour system or a 12-hour system with AM

In Angular, is there a way to determine whether the user's time format is set to 24-hour or 12-hour system? Any help would be greatly appreciated. Thanks! ...

Exploring the paths with node.js variable walking

Currently facing an issue with the npm package "walk". The problem lies in the fact that it requires a string to define the path, which poses difficulty as the path varies based on the directory to be searched. var walkers = walk.walk(""+animeDir+"", opti ...

Unable to determine why node.js express path is not working

const express = require("express"); const app = express(); app.use(express.static("public")); var dirname = __dirname; app.get("/:lang/:app",function(req,res){ console.log(req.params.lang + " " + req.params.app); ...

Translating Django into JavaScript files

I tried to localize the js files following the Django documentation, but unfortunately, it's not working as expected. Here is a summary of my setup: settings.py: LOCALE_PATHS = (os.path.join(BASE_DIR, 'locale'),) urls.py in the main proje ...

Utilizing angular.element().bind with dynamically created element identifiers

I am trying to access an element with a randomly generated ID from my controller. Here is the code snippet: self.componentId = '#' + Math.random().toString(); angular.element(self.componentId).bind('scroll', function () { if (angu ...

Add a container element resembling a div inside a table without implementing the table layout

I am working with a table that is rendered by DataTable, and I have the requirement to dynamically append new elements inside the table like this: The dark grey area represents the new DOM elements that need to be inserted dynamically. The first row cont ...

Ways to retrieve dropdown values

My HTML code is as follows: <select class="height_selected"> <option>Select Height</option> <option ng-model="userHeight" ng-init="1" value="1">123 cm</option> <option ng-model="userHeight" ng-init="2" v ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

leveraging the phonegap plugin with AngularJS application

Currently, I am integrating AngularJS with a custom Cordova plugin that exports an object called deviceAttributes containing various methods. Do I need to make any adjustments in my JavaScript code to access the methods of this object? The console output s ...

Is it possible to use an angular expression as the ng-click function?

I have been searching everywhere for the answer to this question. Within my code, there is an angular object called column.addOnParams. This object includes a child element named rowClick, which can be accessed using column.addOnParams.rowClick. The val ...

You can only use the 'iframe' tag as a child of the 'noscript' tag. Were you trying to use 'amp-iframe' instead? - NextJs

We are currently experiencing an issue with AMP errors. The error message states: "The tag 'iframe' may only appear as a descendant of tag 'noscript'. Did you mean 'amp-iframe'?" It's important to note that custom JavaSc ...

fetch information using ajax and jquery

I'm facing an issue with my ajax request on my website. I'm trying to dynamically fetch pages from a database using jquery and ajax. However, I'm not getting any response, and I'm unsure whether the problem lies in my php code or my j ...

Toggle visibility

Seeking a unique example of a div SHOW / HIDE functionality where multiple divs are populated within the main container. Specifically looking to display new paragraphs or topics of text. I have experience with standard show/hide techniques for collapsing ...