How can I dynamically assign ng-model with a filter for a particular object in an array?

Is there a recommended method for linking an input element to a specific field of an object in an array using its id?

I tried using ng-model along with the find() function from the array prototype. However, the implementation is not working properly as it only populates the input and throws an error at the beginning of page load:

Error: [ngModel:nonassign]

Snippet from AngularJS file:

$scope.myData = [{
    "id": 51,
    "state": "A"
  },
  {
    "id": 52,
    "state": "B"
  },
  {
    "id": 53,
    "state": "C"
  },
  {
    "id": 54,
    "state": "D"
  }
];

$scope.bindObject = function(array, filterby, value, item) {
  let foundObject = array.find(obj => obj[filterby] == value);
  if (foundObject)
    return foundObject[item];
  else
    return $scope.default;
}

Code snippet from HTML file:

<input type="text" ng-model="bindObject(myData, 'id', id_value, 'state')"></input>

Note: The value for id_value is fetched via a web request;

Are there any better or more elegant approaches to achieve this functionality?

Answer №1

thoughts:
1. Instead of working with strings, consider working with objects by returning the object directly. This way, you don't need to worry about knowing the specific model.
2. Add a "model" property to your object for easier manipulation. 3. Implement an if statement in your code.

While not the perfect solution, this should help you make progress.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myData = [{
        "id": 51,
        "state": "A",
        model:"value_of_this_model"
      },
      {
        "id": 52,
        "state": "B"
      },
      {
        "id": 53,
        "state": "C"
      },
      {
        "id": 54,
        "state": "D"
      }
  ];
  $scope.bindObject = function(array, filterby, value, item) {
    let foundObject = array.find(obj => obj[filterby] == value);
    if (foundObject)
      return foundObject;
    else
      return $scope.default;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<div ng-if="bindObject(myData, 'id', 51, 'state') != default">
  {{item = bindObject(myData, 'id', 51, 'state')}}
  <input type="text" ng-model="item.model" >
</div>
</body>

Answer №2

In a previous question, it was mentioned that ng-model cannot be bound to a function. Another issue I encountered was the inability to use the snippet

{{item = bindObject(myData, 'id', 51, 'state')}}
directly on my page. To work around this, I decided to convert my array into a JSON format with the id as the key:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myData = [
      {
        "id": 51,
        "state": "A",
      },
      {
        "id": 52,
        "state": "B"
      },
      {
        "id": 53,
        "state": "C"
      },
      {
        "id": 54,
        "state": "D"
      }
  ];
  
  let temp = {};
  for (let key in $scope.myData) {
            temp[$scope.myData[key].id] = $scope.myData[key];
                        
  } 
  $scope.myData = temp;
  console.log($scope.myData);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<div>
  <input type="text" ng-model="myData[51].state" >
</div>
</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

Finding the text within a textarea using jQuery

My journey with jQuery has just begun, and following a few tutorials has made me feel somewhat proficient in using it. I had this cool idea to create a 'console' on my webpage where users can press the ` key (similar to FPS games) to send Ajax re ...

The MomentJS .format() function accurately displays the date as one day in the past in my local time

After using momentJs to display a date in a specific format in my UTC-4:30 timezone, I noticed that it skips a day. I am currently in the UTC-4:30 timezone. This issue does not occur in all timezones; it works correctly in the UTC-5:00 timezone. The fol ...

Ways to patiently wait in a for loop until the ajax call is completed

I am a beginner in web development and currently working on a small website project that involves using ajax to display new comments. Below is the function I have created: function show_comments() { $('div#P_all_posts>div').each(function () { ...

Verify if the program is operating on a server or locally

My current project involves a website with a game client and a server that communicate via sockets. The issue I'm facing is how to set the socket url depending on whether the code is running on the server or my local PC. During testing and debugging, ...

Implementing Vue directives in separate files and importing them into components: A step-by-step guide

For a project using Vuelidate, I have set up a timeout for validation when a user types something. While I achieved success using mixins, I wanted to adhere to good coding practices by creating a Vue directive without globally registering it, and utilizing ...

Using vue.js to pass route parameters to a component

I'm encountering an issue with passing a route param directly into a component. Despite following various sets of instructions from the documentation (including using the Composition API as shown in the code snippet below), I continue to receive undef ...

Attaching a $UI element to a <div> tag with JQuery may result in unexpected errors and issues

Attempting to connect SagePayments card elements to the paymentDiv. Followed their sample project for guidance, but encountering issues with populating the elements when running the program with a custom Sandbox merchantID and merchantKey. Chrome's de ...

FullCalendar, showcasing real-time event creation as you select dates

I am currently utilizing fullcalendar 4 on my website and I am attempting to incorporate an indicator for when a user selects a date on the calendar. While the background color changes, it's not very visible. My aim is to replicate the functionality ...

It appears that the collection.add() method in connector/node.js only successfully executes one time

Currently, I am experimenting with MySQL Document Store to compare it with our relational tables. To achieve this comparison, I am working on transforming our existing table into a collection. The table contains approximately 320K records that I need to ...

Jquery submenu accordion toggles open and closed with each click

My website has a hamburger menu with an accordion-style submenu implemented using jQuery for devices 1084px and smaller. For larger devices, the menu utilizes a hover-style submenu on desktop. However, I encountered issues when trying to use both the hove ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

Is there a way to transform a JavaScript array into a 'name' within the name/value pair of a JSON object?

Suppose I have a dynamic array with an unspecified length, but two specific values are given for this array. var arrName = ["firstName","lastName"]; I need to create a JSON variable that includes the exact values provided for this dynamic array. Here are ...

Dual Networked Socket.IO Connection

I have set up a node.js server with an angular.js frontent and I am facing a problem with Socket.IO connections. The issue arises when double Socket.IO connections open, causing my page to hang. var self = this; self.app = express(); self.http = http.Ser ...

What's the process for creating a synchronous function in AngularJS?

Is there a way to make storyboard.getAdressTimeLine run synchronously? I need storyboard.drawTimeLine to continue executing only after storyboard.getAdressTimeLine is done for (var i = 0; i < response.data.length; i++) { var obj=response.data[i]; var d ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

Hiding or removing DOM elements with ng-bootstrap pagination

I am in the process of incorporating pagination into my project using ng-bootstrap pagination. In my HTML, I am combining an ngFor loop with the slice pipe to filter elements for display. <tr *ngFor="let bankAccount of bankingAccounts | slice: (p ...

"Utilizing ng class with an array of objects: A step-by-step guide

I am facing a scenario in which my response appears as follows: "currency" : [ { "_id" : ObjectId("584aad5d3e2537613e5f4c39"), "name" : "USD" } ], I need to enable my checkbox based on the currency name. I attempted the followi ...

"Which is better for handling form data: using $.ajax with hidden fields or PHP form

Creating a streamlined admin tool using PHP and JQuery to handle image data management is my current project. The main goal of this utility is to enable an admin to retrieve images from a database, view associated tags for each image, and add new tags as n ...

Implementing route navigation in two components using a click button

To display the content of the Quiz component with the path "/quiz" after clicking a button and fetching the component with the path "/" is my goal. Here is the code snippet from the App.jsx file: <Router> <Routes> <Route ...

Implement a validation function in the "jQuery validation library."

Hello, I am currently using the jQuery validation plugin to validate my form. I am trying to add an additional rule to the validation, but I am struggling to get it to work. The input value should be less than or equal to the previous element's value. ...