AngularJS uses two ng-repeat directives to manage and manipulate data in

I'm implementing a feature where I have two views in my HTML5 code that display the same list.

<div class="list" data-ng-repeat="item in model.items">
    <div class=list-item">
       {{ item.name }} 
        <a data-ng-click="addToList(item)">
            <span data-ng-hide="item.checked">Add</span>
            <span data-ng-show="item.checked">Remove</span>
        </a>
    </div>
</div>

<div class="checkbox-list" data-ng-repeat="item in model.items">
    <div class=list-item">
       <input type="checkbox" data-ng-checked="item.checked" data-ng-click="addToList(item)" />
       {{ item.name }} 
    </div>
</div>

In my controller, I've defined the method in the scope:

function addToList(item) {
    item.checked = !item.checked;

    for (var i = 0; i < this.$scope.items.length; i++) {
        if (this.$scope.items.id == item.id) {
            this.$scope.items[i] = item;
            break;
        }
    }
}

When I click the Add or Remove button, the list updates but the checkbox remains unchecked.

Conversely, when I check a box, the list does not update accordingly.

How can I resolve this issue?

Answer №1

Seems like you're utilizing the controller as syntax.

To make it work, make sure to add the model to the controller itself (assuming that your YourController refers to the controller and that your methods are in the controller):

  for (var i = 0; i < YourController.items.length; i++) {
    if (YourController.items.id == item.id) {
        YourController.items[i] = extension;
        break;
    }
  }

In your YourController, declare:

var YourController = this;

Then in the HTML where you declare the controller, do so as follows:

 ng-controller = "YourController as YourController"

Now, you can access the items in HTML like this:

YourController.items

Answer №2

It appears that you are combining the javascript function declaration syntax with Angular.

When utilizing Angular, it is important to use Angular syntax in order to take advantage of the synchronization between the model and the view. $scope.addToList = function(){}

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  
  
  $scope.model = {};
  
  $scope.model.items = [{"name":"one"},{"name":"two"}]
  
  
  $scope.addToList = function(item) {
    item.checked = !item.checked;
  }
  
  
  
});
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e5eae3f1e8e5f6aaeef7c4b5aab0aafc">[email protected]</a>" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    
    <div class="list" data-ng-repeat="item in model.items">
    <div class="list-item">
       {{ item.name }} 
        <a data-ng-click="addToList(item)">
            <span data-ng-hide="item.checked">Add</span>
            <span data-ng-show="item.checked">Remove</span>
        </a>
    </div>
    </div>

<div class="checkbox-list" data-ng-repeat="item in model.items">
    <div class="list-item">
       <input type="checkbox" data-ng-checked="item.checked" data-ng-click="addToList(item)" />
       {{ item.name }} 
    </div>
</div>


    
    
  </body>

</html>

Answer №3

Make sure to utilize $scope in your function for proper functionality:

$scope.updateList = function (item) {
    item.completed = !item.completed;

    for (var i = 0; i < $scope.todos.length; i++) {
        if ($scope.todos.id == item.id) {
            $scope.todos[i] = updatedItem;
            break;
        }
    }
}

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

Difficulty encountered when displaying JavaScript variable content within HTML in a React component

I'm currently exploring a backend administrative dashboard framework known as admin bro. My current project involves creating a tooltip component, and here is the code I have developed so far. class Textbox extends React.PureComponent { render() { ...

Is it possible to generate a unique name from an array without any repeats?

Update: I am not looking to create a single list, but rather a button that generates a random name when clicked. Objective: Generate a random name from an array by clicking a button. The goal is to display one name at a time randomly without repetition. W ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Using React-router-dom's Link component can cause styling inconsistencies with material-ui's AppBar Button

Exploring the use of a material-ui Button with react-router-dom's Link is showcased here: import { Link } from 'react-router-dom' import Button from '@material-ui/core/Button'; <Button component={Link} to="/open-collective"> ...

Is it possible to have an Iframe that contains content but no src attribute?

During the process of troubleshooting jQuery code on their website (using the Chrome Developer Toolbar), I came across an interesting observation. I found that their examples were embedded within an Iframe: Here, for instance, there is a sample displayed ...

I am experiencing issues with launching chromium while running Puppeteer on Windows 11 using node js v19.4

Upon following the installation instructions in the documentation to install puppeteer with npm install puppeteer, I attempted to run the example for downloading a webpage as a PDF. However, every time I try to execute the code, Node.js returns the followi ...

Move the Div element up and down when clicked

When a tag is clicked, the corresponding div opens and closes. I would like the div to slide down and up slowly instead of appearing immediately. <a href="" class="accordion">Click here</a> <div class="panel" id="AccordionDiv"> ...

Are there any virtual keyboard options available for Angular development?

Is there a virtual keyboard solution for Angular that is fully compatible with the Angular ecosystem? I have looked into the mottie keyboard with an Angular wrapper, as well as this and this The first option lacks full compatibility with Angular's v ...

I'm curious about the significance of the "packages" property in the requireJs config. Can someone explain how it functions?

I'm currently trying to grasp the concept of requireJs and its functionality. In my exploration, I encountered a configuration property called "packages." From what I gather, 'packages' is intended for specifying a complete folder or module ...

update the dropdown values in the database by submitting the form

Members sign up for the website. The administrator will log in and access a list of users. I am attempting to provide an option for the admin to select a checkbox and update the user's status through a dropdown menu submission. When I tested the code ...

Transition the object in smoothly after the slide has changed

How can I make the h4 tags fade in after the divs slide into view, while also adding the class "current" to each visible slide? Check out the example on JSFiddle here. <div class="slider"> <div class="slides"> <div class="slide ...

What advantages does Redux offer?

I've been considering diving into the world of ReactJS lately and I could really use some guidance on when to incorporate Redux. The concept seems a bit complex to me, especially coming from an Angular2+ background. Although I've come across sev ...

Submitting information through Ajax

Struggling to update a field in my database using AJAX. No errors in console, but the DB won't update. Anyone able to help? AJAX: function ajaxUpdate() { var arr = {var1: name, var2: age}; $.ajax({ url: 'aja ...

What is the process for running the 'ng build' command within Azure DevOps?

When working in Azure DevOps, I utilize the 'npm task' to install a package. The subsequent step involves utilizing a Command Line task to execute the 'ng build' command. Unfortunately, an error message stating that the ng command does ...

The JavaScript .load() function fails to run

Attempting to create a straightforward Newsfeed page based on user interests. Here is the code I have implemented for this purpose. The issue I'm facing is that while the code works fine on my local server, it encounters problems when running on an on ...

Flipping numbers in Arabic font using PDF kit

Currently, I am utilizing the pdfkit library in my Node.js application for PDF generation. However, I encountered an issue while attempting to incorporate Arabic text. The problem lies in the fact that it consistently rearranges the numbers within Arabic t ...

Iterate through each entry in the database and identify and fix any duplicate records

In my form, I have a JSON array that includes the name and value of each input. I am attempting to add an "optionprix" attribute for each input with the "optionname" class based on the corresponding value of the input with the "optionprix" class. Here is ...

Automate the execution of webdriver/selenium tests when a form is submitted

I am currently faced with a challenge in setting up an application that will automate some basic predefined tests to eliminate manual testing from our workflow. The concept is to input a URL via a user-friendly form, which will then execute various tests ...

Is there a way I can finish animating these divs in a diagonal motion?

I successfully made the blue and red divs move diagonally and switch positions. Now I am looking to achieve the same effect with the green and pink divs using a similar function. I am unsure about setting the position of both divs to 0 and 350 for those p ...