The ng-class directive is not functioning properly when used in conjunction with $scope.$watch on the second click

Hey there, I've encountered an issue with my code. Everything works smoothly when toggling the checkbox using ng-click and dynamically updating it based on input numbers in the input tag through $scope.$watch(). However, when I try to uncheck the 'Shopping' label's checkbox using the 'toggleCheckBox()' function after entering numbers, the ng-class doesn't seem to work properly. Even though $scope.$watch() displays "Hello World!", it fails to initialize $scope.checkShopping = true. Any ideas on what could be causing this problem? Here's the code. Appreciate your assistance!

$scope.toggleCheckbox = function (mainModel, subModel) {

        var index = $scope[mainModel].indexOf(subModel);
        if (index >= 0) {
            $scope[mainModel].splice(index, 1);
        } else {
            $scope[mainModel].push(subModel);
        }
    };


$scope.$watch('Shopping',function(){
  if($scope.Shopping > 0){
    $scope.checkShopping = true; //this code is not working on 2nd input. The ng-class is not setting to 'TRUE'
  console.log("Hello world!");
  }
});
.checkListHolder {
width: 100%;
display: block;
overflow: hidden;
}

.checkListHolder > li {
display: inline-block;
width: 100%;
float: left;
overflow: hidden;
padding: 5px 0;
}

.checkedListItem .checkboxList {
background-image: url(../images/form-icons/checkbox-on.png);
}

.checkboxList {
width: 20px;
height: 20px;
background-repeat: no-repeat;
background-position: center;
background-image: url(../images/form-icons/checkbox-off.png);
margin: 0 10px 0 0;
cursor: pointer;
}

.checkboxLabel {
width: auto;
float: left;
overflow: hidden;
color: #FFF;
font-size: 14px;
font-family: "Open Sans", sans-serif!important;
}
<li ng-class="{checkedListItem : checkShopping == true}">
  <div class="checkboxList" ng-click="toggleCheckbox('PleasureVacationList','Shopping')">  </div>
  <div class="checkboxLabel">Shopping</div>
</li>
<li>
  <input type="number" ng-model="Shopping">
</li>

Any insights on what might be causing this issue? Thank you for your help

Answer №1

When assigning a variable directly on the scope, one issue arises due to changing the pointer instead of just the value. As a result, angular's digest cycle fails to detect the change. There are several solutions available:

/* 1: apply the function in the digest cycle */
$scope.$apply(function() {
    $scope.checkShopping = true;
});

/* 2: apply to the whole digest cycle */
$scope.checkShopping = true;
$scope.$apply();

/* 3: use an object with initialization */
$scope.shopping = {
    checkShopping: false
}

// This way, angular's digest cycle will recognize the following change:
$scope.shopping.checkShopping = true;

Here's an insightful explanation on the reasons behind this phenomenon

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 it possible to implement an automatic clicking function on a bootstrap navigation bar similar to a carousel?

I am working on a website with a bootstrap navigation bar similar to the one shown in this image : bootstrap nav <ul class="nav nav-tabs" id="tab_home" role="tablist"> <li class="nav-item" role="pres ...

Retrieve the total count of tables within a specific div element

If I have an unspecified amount of tables within a div, how can I determine the total number of tables using either plain JavaScript or jQuery? ...

Consolidate two AJAX requests into a single callback

I'm developing a Chrome extension and facing the challenge of merging two separate AJAX calls into one callback upon success. What would be the most efficient approach to achieve this? Auth.prototype.updateContact = function(id, contact_obj) { var ...

Filtering a Two-Dimensional Array Using JavaScript

I am working with a basic 2D array that contains x, y coordinates as shown below: var c = [ [1,10], [2,11], [3,12], [4,13], [5,15] ]; I want to know how I can extract pairs from the array that meet specific conditi ...

Sort table rows by checkbox value in javascript

Is there a way to use javascript or JQuery to group the rows in this table by Office or Age based on the checkbox option selected? For example, if the Office checkbox is checked, the table rows should be grouped by Office. If the Age checkbox is checked, ...

React's Dynamic Table fails to rerender when updated values are placed in the same row and under the same header

Here is the table generated by my functional component: <table class="table"> {/* Consonant Table */} <tr> <th colSpan="2">---</th> {headersPOA. ...

Unlocking the hidden treasures: Integrating nested values into Material Table fields via column linking

I am currently working on creating a table with nested data that looks like this: [{ id: 24, name: "DANIEL TSUTOMU OBARA", number: "134", phone: "11111111111", rg: "4034092666", EmployeeStatus: { crea ...

Altering the properties of every item within a v-for loop's array

I'm currently exploring Vue's approach to writing JavaScript. Let's consider this situation: In the .vue template <button v-on:click="biggerFont()" class="btn btn-s btn-default" type="button" name="button">A</button> < ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

The AngularJS Service fails to update when the user clicks on a link with varying $routeParams

When using a service in angularJS that passes a JSON object to a controller upon clicking a specific link, /match/id-:matchId', it references the $routeParams of the :matchId to determine which JSON object to request. The issue arises when a user cli ...

Sharing the port of a local Node.js HTTP server (which is being executed in an Electron environment) with an Angular

Running a RESTful node JS Http server on localhost within an electron app, listening on port 0 to get a random free port. How can I access this randomly assigned port in my Angular code to determine the URL for XHTTP requests? Nodejs restapi server runnin ...

Simple Method for Converting JSON to CSV (Even with Arrays as Fields)

Is there a way to convert my parse.com JSON data into a CSV file where each number within an array is saved within its own field? I have tried using various online converters, but they fail due to the large size of my data. I am looking for a solution that ...

Angular.js model that is updated by checkboxes

In my project, I have created a model that is linked to several other models. For instance, let's consider a scenario similar to a Stack Overflow question associated with tags. Before making a POST or PUT request, the final Object may appear like this ...

differences in the reaction to special characters between IE10 and IE8

After searching extensively on Stack Overflow, I have yet to find a solution that addresses the unique challenge presented by my question. I have discovered that both dot and delete keys yield the same keycode (46) when checked for special characters. How ...

Adding data to a defaultContent JSON column in JQuery DataTable using JavaScript

I am working with a dynamic jQuery data table. The final column in my table allows users to delete rows, but I am having trouble passing the itemId value to the specified function within the button's onClick attribute. Here is the code I have tried s ...

Tips for arranging objects consecutively with angular's *ngFor

I need help with displaying items inline instead of in different rows. I have searched online for solutions, but couldn't find a relevant answer. Can anyone assist me with this? Thank you! https://i.sstatic.net/AvlMj.jpg <!DOCTYPE html> <h ...

Tips for creating read-only checkboxes with multipledropdown.js in Angular.js

I am trying to make all checkboxes in a multiple dropdown list readonly using Angular.js with the multipledropdown.js plugin. My code snippet is as follows: <div class="col-md-6" ng-show="sub_sub_menu"> <div class="input-group bmargindiv1 col-md- ...

Eliminate the hover background color from the bootstrap nav-link

I've been struggling to eliminate the background color of the nav-link hover by setting it to transparent, but it still displays a background when hovered. I want to change the hover color for the text only, similar to the nav-brand, but I can't ...

Combining array elements with unique property labels

I have two arrays of objects containing the properties: name, value, and id Array A ArrayA: [{ name: , value: , key: }, ]; There is another array of objects, but with different property names ArrayB: [{ user: “userA” , email: ...

Is there a way to simultaneously adjust the width of all right or left elements?

I am working with a group of sibling div elements and I need to adjust their widths based on the drag and resize of one particular div. When the div is being resized to the west or east, I want to increase or decrease the widths of the other sibling divs ...