I am having trouble with AngularJS not enabling my checkbox when using a hyperlink with the ng-click event

I’m encountering an unusual situation where my checkbox isn’t getting ticked using Angular (1.5). Even after checking in chrome Batarang, everything seems fine but when I click on my link, the checkbox remains unchecked!?

Within an ng-repeat loop, I have an array being displayed. Inside this loop, there’s a checkbox and a hyperlink that should control the checkbox.

Is there anyone who can figure out why the hyperlink is failing to check the checkbox?

Thank you in advance,

Markup

<tr ng-repeat="o in vm.myArray track by o.Id"> 
  <td>

      <!-- This works (changes the checkbox to checked)-->
      <a href ng-click="o.Highlight=true">Just to test it (this works)</a> 

      <input type="checkbox" ng-model="o.Highlight" ng-click="vm.highlight(vm.myArray.Days, o.Name);" style="width: 15px" />

      <!-- This fails (I'm expecting it to check the checkbox) -->
      <a href ng-click="vm.highlight(vm.myArray.Days, o.Name)">
          {{o.Name}} 
      </a>
  </td>

</tr>

This function simply iterates through an array of objects that contain a "Highlight" property (boolean) which determines UI elements. The Highlight property should toggle the checkbox status.

Despite Chrome batarang showing the correct Highlight property setting, the checkbox doesn’t toggle as expected.

Highlight method in controller

(function() {
    "use strict";

    angular.module("bla").controller("homeCtrl", ["stuff", function (stuff) {
    var vm = this;
    vm.highlight = highlight;

    // Iterate through array items and toggle item highlighting if fieldToHighlight matches the item.Name.
    function highlight(collection, fieldToHighlight) {

        for (var i = 0; i < collection.length; i++) {
            var element = collection[i];

            if (element.Items != null) {
                for (var counter = 0; counter < element.Items.length; counter++) {
                    var item = element.Items[counter];

                    if (fieldToHighlight == item.Name) {
                        if (item.Highlight) {
                            item.Highlight = false;
                        }
                        else {
                            item.Highlight = true;
                        }
                    }
                }
            }
        }
    }

Update after comments

Angular plugin for Chrome

The Highlight property is initially set to false. When clicking the test hyperlink, the property correctly changes to true.

angular plugin for chrome showing property correct data type

Update 2 - shows chrome debugging is setting the value correctly

During debugging, the Highlight property behaves correctly, even though the UI is not updating.

code being debugged showing the highlight is working even though the ui is not updating

Update after comments (13th december 2016)

Comments within the code:

<tr ng-repeat="o in vm.myArray track by o.Id">
    <td>
      <!-- checkbox -->
      {{o.Highlight}}
      <!-- clicking this changes the echoed variable above immediately but doesn't affect the checkbox based on o.Highlight -->
      <input type="checkbox" ng-click="vm.highlight(o);" ng-model="o.Highlight" />

      <!-- name -->
      <!-- clicking this toggles the correct behavior in the UI dependent on the o.Highlight property but doesn't change the checkbox state -->
      <a href ng-click="vm.highlight(o)">{{o.Name}}</a>
    </td>
</tr>

Answer №1

Here are a few queries and solutions for you :-)

  1. Why is the array vm.myArray used in the ng-repeat, but in the vm.highlight() method, vm.myArray.Days is treated as an object? It raises a question about the inconsistency in treating myArray as both an array and an object.
  2. Furthermore, within this method, the comparison of o.Name with the deep level property like vm.myArray.Days[0].Items[0].Name shows two different formats. What is the reason behind this difference in format?

To address these questions effectively, it would be helpful to have access to the actual myArray data collection.

Even without that information, assuming myArray is being considered as an array rather than an object, I can propose the following alternative answers:

Response 1:

If you aim to toggle the highlight state, try using o.Highlight=!o.Highlight instead of o.Highlight=true as shown below:

<a href ng-click="o.Highlight=!o.Highlight">Just to test it (this approach should work)</a> 

Response 2:

If you prefer having the same toggle effect while incorporating other controller functions, you can encapsulate the logic as follows:

<a href ng-click="vm.highlight(o)">{{o.Name}}</a>

function highlight(obj) {
   obj.Highlight = !obj.Highlight;
}

Response 3:

In case you want to compare the Name property against an array, consider the following implementation:

<a href ng-click="vm.highlight2(vm.myArray, o)">{{o.Name}}</a>

function highlight2(collection, obj) {
  for (var i = 0; i < collection.length; i++) {
    var item = collection[i];
    if (obj.Name == item.Name) {
       obj.Highlight = !obj.Highlight;
    }
  }
}

Note: If your array structure differs or if there are inconsistencies, the provided responses might not yield the intended results. In such cases, sharing the sample data from vm.myArray is crucial.

Sample code snippet:

(function() {
    "use strict";
    angular.module("bla", []);
    angular.module("bla").controller("homeCtrl", [ function () {
    var vm = this;
    vm.highlight = highlight;
    vm.highlight2 = highlight2;
      
    vm.myArray = [{Id: 1, Name: 'Item 1'}, {Id: 2, Name: 'Item 2'}, {Id: 3, Name: 'Item 3'}];

    // Iterate through array and toggle the Highlight field when matching the item.Name.
    function highlight(obj) {
       obj.Highlight = !obj.Highlight;
    }
      
    function highlight2(collection, obj) {
      for (var i = 0; i < collection.length; i++) {
        var item = collection[i];
        if (obj.Name == item.Name) {
           obj.Highlight = !obj.Highlight;
        }
      }
    }

}]);
  
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="bla">
<table ng-controller="homeCtrl as vm">
  <tr ng-repeat="o in vm.myArray track by o.Id"> 
   <td>

      <a href ng-click="o.Highlight=!o.Highlight">Just to test it (toggle feature)</a> 

      <input type="checkbox" ng-model="o.Highlight" ng-click="vm.highlight(o);" style="width: 15px" />
      Link 1: 
      <a href ng-click="vm.highlight(o)">
          {{o.Name}} 
      </a>&nbsp;
      Link 2: 
      <a href ng-click="vm.highlight2(vm.myArray, o)">
          {{o.Name}} 
      </a>
   </td>

  </tr>
</table>
</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

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

Is there a way to disable the default UI views for login and registration in IdentityServer3?

As I delve into incorporating IdentityServer3 into my architectural framework, I'm intrigued by the concept of registering Clients, Users, and Scopes. However, I find myself hesitant about utilizing IdentityServer3's default login and registratio ...

Creating a function that assigns an anonymous function which in turn returns another anonymous function

Can you explain the difference in JavaScript between these two code snippets? var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { loadData(e.target.result); }; })(file); reader.readAsText(file); a ...

Effective methods for eliminating Stripe's iframes

I am integrating Stripe Elements using vue-stripe-elements-plus on a single page application. I want to completely unload Stripe after the user leaves the credit card module, but it seems more complicated than expected. Even after unloading it in the comp ...

What is the proper way to utilize the uppercase method while ensuring that Turkish characters are not permitted?

Here is the code snippet I am working with: <input type="text" style="text-transform: uppercase" /> When using this code, characters like ü are transformed to Ü. However, I want ü to be transformed to U, so for example, Gülay should become GULA ...

Having trouble grasping the inner workings of code while iterating through a JSON array in ReactJS

Currently, I am immersed in a school project that requires me to develop a simple CRUD web application. After weighing my options, I decided to utilize Spring Boot + ReactJS for this endeavor. The progress has been smooth so far, but I must admit that part ...

Adding a Javascript file to the requirejs-config.js file in Magento 2

How can I properly load a JS file using requirejs? <script type="module" src="https://unpkg.com/@google/model-viewer/dist/model-viewer.min.js"></script> Here is my requirejs-config.js file: var config = { paths: { mod ...

Tips for organizing the outcome of a seamless web scraping operation with Apify and Puppeteer

Extracting data from a table on the designated URL using Apify and Puppeteer is my current goal: https://en.wikipedia.org/wiki/List_of_hedge_funds The desired outcome should be an array of objects. Each element in the array must represent a <tr> ro ...

Incorporating Bootstrap JS into Next.js

Currently, I am in the process of learning next.js and experimenting with incorporating Bootstrap into my projects. To begin, I initiated a new project using npx create-next-app@latest my-app, utilizing the newly created "app" directory structure. Follow ...

Jsonip.com is providing both internal and external IP addresses

I'm utilizing to retrieve the IP address of users. In some cases, it is returning both an internal and external IP as a string separated by commas. I am interested in only obtaining the external IP address. Can I assume a specific order for the retur ...

Ways to determine if a web browser is executing javascript code (without altering the javascript on the webpage)

Working on creating a custom PHP client for Selenium, I've encountered an issue with implementing the waitForPageToLoad() function: The problem lies in just checking the document.readyState, as there could be JavaScript scripts running on the page (l ...

Customize the href option with Fancybox plugin in real-time

My issue involves working with links such as: <a href='http://mysite.com/comment/123/edit' class='fancybox'>Edit comment</a> I am utilizing the Fancybox plugin: $(".fancybox").fancybox(); Upon clicking the link, I am dir ...

The mystery of a JQuery response that remains elusive

Despite my best efforts, I've been struggling for hours with what seems like a simple and well-documented task. All I want to do is retrieve the result of a $.getJSON query without appending it to a div. While I can successfully alert the result withi ...

Resolving the Table Issue with 'onclick' in Javascript

Apologies for the lack of creativity in the title, I struggled to come up with something fitting. Currently, I am engaged in the development of a user-friendly WYSIWYG site builder. However, I have encountered an obstacle along the way. I've devised ...

What steps should I take to resolve the issue with this error message: Error: listen EADDRINUSE

How can I resolve the following issue? system: gulp npm windows issue: ... Oh no. Encountered error listen EADDRINUSE 127.0.0.1:35729 ... Error: listen EADDRINUSE 127.0.0.1:35729 at Object._errnoException (util.js:1021:11) at _exce ...

The "smiley" character added to the information during an Ajax call

Encountering an unusual issue. A colon (:) character is being appended to the JSON data sent to the server via AJAX request. https://example.com/image1.png The colon character seems to appear after sending the JSON, but it does not show up when inspectin ...

Guide to sending a variable's value through AJAX in a PHP function

In my current project, I am working with two input fields named A and B. The values for these fields are fetched from a database, where the value of field B depends on the value of field A. To update the value of field B dynamically, I am using an AJAX cal ...

Guide to finding your way to a specific section in React

I attempted to navigate to a particular section within a page. I also tried to include an id in the component, but it didn't function as expected <Login id ="login_section > ...

The functionality to redirect in Wordpress Contact Form 7 based on the value of a radio button selection does

For the past 5 hours, I have been diving deep into Contact Form 7 redirects that are based on values. Despite my efforts, I am unable to figure out why my code isn't functioning properly. Is there anyone who can spot the issue? Contact Form Radio But ...

Data will not bind with Laravel and Vue

I am currently working on a Laravel project and trying to develop a basic editing feature for posts. My approach involves using Vue.js 2 to bind the data, but unfortunately, I am facing issues with displaying it - I'm not quite sure what's causin ...