How to iterate through classes in AngularJs and assign values to models

It dawned on me that I may not be approaching or researching this correctly. My goal is to select a group of DOM elements by their class and then assign values to their ng-model attributes.

To clarify in pseudo code:

For each element with the class "foo":
    Set x.modelValue = 1

Answer №1

First and foremost, it is highly advisable to reconsider the structure of your architecture. It is more efficient to have your view (DOM) depend on the values in your model rather than the reverse.

However, if for some reason you must proceed in this manner, here are some steps you can take:

  1. Develop a directive with the same name as your class
  2. Restrict its usage to classnames exclusively
  3. In the link function, instruct it to set the value

See a demo here

.directive('foo', function() {
  return {
    restrict: 'C',
    require: '?ngModel',
    link: function(scope, el, attrs, modelCtrl) {
      if(modelCtrl) {
        modelCtrl.$setViewValue('foo')
        modelCtrl.$render()
      }
    }
  }
})

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

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

The function queryDatabases is not supported in the DocumentDB JavaScript API

Currently, I am developing a service for Azure Functions using JavaScript/Node.js. However, I encounter an error when trying to access the function DocumentClient.queryDatabases. Despite having the correct references installed in Visual Studio Code and bei ...

Is the MUI Drawer Open 20% of the Time?

One issue I'm facing is with my MUI drawer - it's supposed to close after a menu item is clicked, but sometimes, about 1 out of 5 times, it remains open. I have based my current code on a helpful post on Stack Overflow. Take a look at the code s ...

Guide to switching content within a DIV when the up and down buttons are pressed using JavaScript and jQuery

I have a functional code with a timeline where each event is connected to the other. There are buttons to delete and copy data, but I want to implement functionality for swapping elements when the up or down button is clicked. I have provided a sample code ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

Is the browser capable of storing and managing timer IDs that are currently in use?

Is it the browser's responsibility to track active setInterval and setTimeout IDs, or is this solely left up to the developer? If the browser does keep track of them, can they be accessed through the Browser Object Model (BOM)? ...

Having trouble with JQuery click function not executing on initial click?

As I scoured through various resources looking for solutions to issues similar to mine, I stumbled upon numerous helpful insights. However, after going through approximately 15 of them, I hit a roadblock in finding someone who has encountered the exact sam ...

Utilizing a Single Variable Across Multiple Middlewares in nodeJS

I encountered an issue where I am attempting to utilize one variable across two middlewares, but it displays an error stating that the variable is not defined. Here is an example of my situation: //1st middleware app.use((req, res, next) =>{ cont ...

While using Ckeditor, typing or deleting text will cause an input checkbox to become unchecked and its value to be altered

Whenever I try to make any changes or use the backspace key in Ckeditor, the checkbox gets unchecked and the value resets to 0. Despite my efforts, I have been unable to find a solution to this issue. How can I resolve this problem? CKEDITOR.replace( &ap ...

Accessing enum values in a view with Typescript and AngularJS version 1.5

Recently started working with Angular 1.5 and Typescript I have a service that returns data in an array format called devices.headerEntries: [{name:id,value:45} ,{name:Mode,value:1},{name:State,value:2},{name:serialnum,value:123434} I created a componen ...

Exploring the back button event in Angular JS and Phonegap

In my MainCtrl, I have implemented a backstack for history. Here is the code: $scope.urlHistory = []; $scope.$on('$routeChangeSuccess', function () { if ($location.$$absUrl.split('#')[1] !== $scope.urlHistory[$scope.urlHistory.len ...

Transferring PHP Array information to JavaScript

I'm facing an issue with transferring data from a PHP function querying a mySQL database to a JavaScript function for use in a plotly graph. Although I can successfully retrieve the data in PHP, I encounter a problem when trying to access it in my Jav ...

The initial time delay set by setTimeout does not seem to have any impact

The issue with setTimeout not working as expected lies in its execution order. The code below it gets executed without waiting for the delay specified in the first argument of 'setTimeout' to run. (function() { var a = ['#bird',&ap ...

Having trouble with the installation of nodemon globally on macOS Mojave?

When using the Visual Studio Code terminal, I ran the following command: npm install -g nodemon The output in the terminal showed: npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! syscall access n ...

What is the best way to organize JavaScript code for handling multiple variables from multiple form elements while also preserving the selected choices?

For instance, suppose I have an HTML form like this: <form role="search" method="get" id="searchform" action="" > <!-- DIRECT SEARCH INPUT TO SEARCH STRING --> <input type="text" value="" name="s" id="s" /> <input type=" ...

Is there a way to display the HTML input date by simply clicking on text or an image?

I need to display a date picker when I click on specific text or an image. I am working with reactjs and utilizing the HTML input type="date", rather than the React-datepicker library. Here is the code snippet: import { useRef } from "r ...

What purpose does tagging serve in my template for polymer property binding?

I'm currently exploring the way Polymer handles the rendering of properties in a custom element's template. I've come across some interesting behavior that I haven't been able to fully grasp yet. Specifically, I noticed that certain pro ...

What options are available for managing state in angularjs, similar to Redux?

Currently, I'm involved in an extensive project where we are developing a highly interactive Dashboard. This platform allows users to visualize and analyze various data sets through charts, tables, and more. In order to enhance user experience, we ha ...

Sign in with Google / External authentication service

Currently working on an AngularJS application that includes Google login functionality. To implement this feature, I found a useful guide at the following link: . Additionally, there is a script that is called when the page loads: <script type="text/j ...

I am looking to pass a value to a JSON object in AngularJS

Could someone provide me with examples of using $http.post in AngularJS? I'm new to this framework and I'm trying to update a JSON file while gathering user input. I want to modify the values in the file but I seem to be having trouble doing so. ...