Update and verify a collection of objects in real-time

I have a callback function that retrieves a data object from the DOM. Each time an item is selected, the function returns an object like this:

$scope.fClick = function( data ) {                 
                    $scope.x = data;
                }

When an item is selected from the dropdown, the object looks like this:

{  name: "English",    ticked: true    }

When the item is deselected, the object returned is:

{  name: "English",    ticked: false   }

I have an array called $scope.output to store these returned objects. What I want to achieve is to add an object to $scope.output only if there isn't already an object with the same "name" value present in the array. Currently, both

{ name: "English",    ticked: false   }
and
{   name: "English",    ticked: true    }
are added to the array. I want to update the "ticked" property instead. For example, if
$scope.output = {   name: "English",    ticked: false   }
and the function returns { name: "English", ticked: true}, I want it to update the existing object's "ticked" property:
$scope.output = {   name: "English",    ticked: true    }

This is what I have attempted:

$scope.fClick = function( data ) {                 
                    $scope.x = data;
                }
                $scope.$watch(function () {
                return $scope.y = $scope.x;
                },function (newValue, oldValue) {
                    var id = $scope.output.indexOf(newValue);
                    if(id === -1){
                        $scope.output.push(newValue);
                            }
                    else {
                        $scope.output[id].tick = newValue.tick;
                    }
                    console.log($scope.output);

            },true);

How can I make this implementation work as intended?

Answer №1

Access and manipulate selected values, names, and text using Angularjs isteven-multi-select

<div isteven-multi-select
    input-model="marks"
    output-model="filters.marks"
    button-label="name"
    item-label="name"
    tick-property="ticked"
    selection-mode="multiple"
    helper-elements="all none filter"
    on-item-click="fClick( data )"
    default-label="Select marks"
    max-labels="1"
    max-height="250px">
</div>

Adding items

$scope.marks= [
    { name: 'Mark I', value: 'Mark i', text: 'This is Mark 1', ticked: true },
    { name: 'Mark II', value: 'Mark ii', text: 'This is Mark 2' },
    { name: 'Mark III', value: 'Mark iii', text: 'This is Mark 3' }
];

Obtaining selected item (on change)

$scope.fClick = function (data) {
    console.log(data.name);
    console.log(data.value);
    console.log(data.text);
    return;
}

Programmatically selecting an item

$scope.abc = function (data) {
    console.log(data.element1, data.element2);

    angular.forEach($scope.marks, function (item) {
        if (item.value == data.element1) {
            item.ticked = true;
        }
        else {
            item.ticked = false;
        }
    });
}

Deselecting an item

$scope.marks.map(function (item) {
    if (item.value == "")
        item.ticked = true;
    else
        item.ticked = false
});

Answer №2

To create a simulated key/value map, you can follow these steps.

Controller

(function(){

function Controller($scope) {

  $scope.data = [
    {name: 'English', ticked: true},
    {name: 'French', ticked: false}
  ];

  //Create a key-value map
  $scope.output = {};


  $scope.update = function(index){
    //Toggle the ticked value
    $scope.data[index].ticked = !$scope.data[index].ticked;

    //Update the map value
    $scope.output[index] = $scope.data[index].ticked;
  }

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

When updating $scope.output, existing keys will be replaced with new values, otherwise new key-value pairs will be created.

HTML

  <body ng-app="app" ng-controller="ctrl">

    <ul>
      <li ng-repeat="item in data">{{item.name}} {{item.ticked}} <button type="button" ng-click="update($index)">update</button></li>
    </ul>


  </body>

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

Attempting to generate a nested array structure in order to produce a JSON object for output

I am currently working on a JavaScript script that interacts with the Netsuite ERP platform to retrieve data. Currently, the script is returning data in an array format, specifically product information. While this is functional, I would prefer it to retu ...

Retrieve the present value from a Selectpicker using jQuery within the Codeigniter Framework

I attempted to use DOM manipulation to retrieve the value of the currently selected option from the selectpicker. My goal was to have the value of the selectpicker id="service_provider_select" printed first. However, whenever I changed the option using the ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

I'm attempting to solve the retrieved data from a firebase query, but unfortunately, the data is refusing to resolve

I've been attempting to retrieve data from firebase using Node.js, but I'm having trouble resolving it. Specifically, I need to extract the timestamp from the data stored in firebase. I've tried using promises and forEach loops, but haven&a ...

"Upon clicking the login button, I encountered an issue with redirecting to the destination

I've been working on developing a login page using Angular framework. However, I'm facing an issue where I am unable to access the destination page after entering the login credentials. Below, you can find a snippet of the code from the login.com ...

What is the process for confirming the authenticity of lengthy passwords with bcrypt?

"I encountered a problem that I just can't seem to solve. I set up an authentication flow using JWT with access and refresh tokens. The refresh tokens expire after a long time period, and they can be reset to prevent unauthorized use of stolen refresh ...

CSS Flexibility in Action

Presently, my tab bar has a fixed look as shown here: https://codepen.io/cdemez/pen/WNrQpWp Including properties like width: 400px; etc... Upon inspecting the code, you'll notice that all the dimensions are static :-( Consequently, I am encountering ...

What are the best methods for adjusting the size of a game's

I create games using HTML5/CSS/JS, but I am struggling to figure out how to make them scale to different screen resolutions. It seems like a simple task, but I can't seem to grasp it. SOLVED var RATIO = 480 / 800; // Initial ratio. function resize() ...

Why is my AngularJS application triggering two events with a single click?

<button id="voterListSearchButton" class="serachButton" ng-click="onSearchButton1Click()">find</button> This button allows users to search for specific information: $scope.onSearchButton1Click = function() { var partId = $("#partIdSearch" ...

How to Implement Multiple OR Statements in SharePoint 2010 Using Jquery and JSON Rest

Struggling to create a multiple OR variable, but it just won't work. Is there an issue with my syntax or logic? var category = (i.Category == "Electric" ? "E" : i.Category == "Power Module" ? "PM" : i.Category == "Branch Office" ? "BO" : ""); After ...

Creating arrays by repeatedly assigning lists within lists

I am working with a list of lists and my goal is to assign each sublist to an array with a specific shape. Here is the progress I have made so far: N=23 # Reading the file in lines with open('ircforward.xyz','r') as f: lines = f.r ...

Having trouble loading script files with JSDOM in NodeJS?

I'm currently experimenting with loading an HTML page in jsdom to generate graphs, but I'm facing challenges in getting the JavaScript to execute. Here's the HTML page I'm trying to load, which simply renders a basic graph: <html&g ...

How much worth does an unfilled text input box hold?

I've been working on integrating a search feature and I'm having an issue with the functionality. Below is the code snippets for both HTML and JS: HTML <form> <input type="text" ng-model="searchVar" class="searchbox"> <in ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

Which event in the listbox should I trigger to adjust the scroll position?

My webpage includes a listbox inside an update panel. I've managed to capture the scroll position, but now I'm facing difficulty in identifying the right javascript event to call my function for setting the scroll position after the update panel ...

Issue with JQuery delay functionality not activating correctly upon clicking an <a> tag

When I click on an <a> tag, I want to display a div and wait for 10 seconds before redirecting. However, the div is currently being shown immediately without waiting. Here is the HTML code: <a class="clickHereToDisplay" href="http://www.google.c ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

Challenges with sorting in AngularJS

I recently started learning angularJS and have been experimenting with the ng-repeat feature and $http service. After selecting a webservice to fetch data from, I successfully implemented it into the ng-repeat. However, I am now trying to sort the table A ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

"Step-by-step guide on uploading multiple images to a Node server and storing them in

Hey everyone! I'm currently working on a project using React and MongoDB. Users are required to register and login before accessing the app. Once logged in, they can input their name, number, and images through a form. However, I've encountered a ...