Store the results of the ng-repeat function in an Array

Within my MongoDB attributes collection, I am looking to include a new field "odoo_name" for each attribute and save it.

For instance, with 100 attributes, each one will now have an odoo_name field in order to update the existing database.

Issue : when I check console.log(odoo_name), it displays undefined, indicating that it cannot recognize the name entered in the input field.

I modified the ng-submit function to saveOdooNames(vm.localAttributes) and while I am able to retrieve all data, accessing the ng-model still returns undefined. (console.log(inputs.odoo_name)

<form ng-submit="saveOdooNames(i)">
      <button>Save</button>
      <div class="col-md-12">
        <ul class="grid">
          <li data-ng-repeat="i in vm.localAttributes">
            <label>
              <div class="attribute-msl-link-label-wrap">
                <div class="attribute-msl-link-label">
                  <span class="attribute-icon">
                    <i class="glyphicon glyphicon-folder-open"></i>
                  </span>
                  <span class="attribute-number">{{ i.number_id }}</span>
                  <span class="attribute-title" title="{{i.project.name}}">{{ i.name }}</span>
                  <input ng-model="i.odoo_name" type="text" class="form-control"/>
                  <a href="javascript:void(0)" class="del-attr" data-id="{{ i._id}}" data-parent="0">
                    <i class="glyphicon glyphicon-trash"></i>
                  </a>
                </div>
              </div>
            </label>
          </li>
        </ul>
      </div>
    </form>

This code snippet is from my controller :

$scope.saveOdooNames = function (o) {
  var inputs = [];
   inputs.push(o);     
  $http({
    method: 'POST',
    format: 'json',
    url: '/api/odoonames',
    headers: {
      'Content-Type': 'application/json'
    },
    data: { _id : inputs._id,
            odoo_name : inputs.odoo_name }

  }).then(function (success) {
    console.log('Success ' + JSON.stringify(success));
  }, function (error) {
    console.error("Error " + JSON.stringify(error));
  });    
};

Note: Saving fields individually works fine, but I require a bulk save for these fields.

EDIT :

I changed ng-submit="saveOdooNames(i)" to ng-submit=vm.localAttributes)"

End Edit

The Save button should store all input data in an Array named "inputs"

Answer №1

Instead of passing parameter "i" which is undefined due to the nested ng-repeat, it is recommended to directly link the save function to the button. By utilizing vm.localAttributes, you can easily access your data within the function.

<form>
    <button ng-click="saveOdooNames(vm.localAttributes)">Save</button>
....

Answer №2

When using the $http method, make sure to return it as a promise. It's important to handle the data properly by pushing it into an array and assigning objects correctly without forgetting to reference the index of the array. Adding a return statement is essential, but you may still need to refactor the data being assigned in the data params. Hopefully, these tips steer you in the right direction.

function processNamesRequest(inputs) {
  return $http({
    method: 'POST',
    format: 'json',
    url: '/api/odoonames',
    headers: {
      'Content-Type': 'application/json'
    },
    data: {
      _id: inputs._id,
      odoo_name: inputs.odoo_name
    }

  }).then(function(success) {
    console.log('Success ' + JSON.stringify(success));
  }, function(error) {
    console.error("Error " + JSON.stringify(error));
  });
}
$scope.saveOdooNames = function(o) {
  //if you dont need an array here 
  //i would just send `o` as is in the request
  var inputs = [];
  inputs.push(o);
  return processNamesRequest(inputs)
};

/*Refactored: I'd also consider putting all http requests inside of a factory or a service.*/

function processNamesRequest(input) {
  return $http({
      method: 'POST',
      format: 'json',
      url: '/api/odoonames',
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        _id: input._id,
        odoo_name: input.odoo_name
      }

    })
    .then(function(success) {
      console.log('Success ' + JSON.stringify(success));
    })
    .catch(function(error) {
      console.error("Error " + JSON.stringify(error));
    });
}
$scope.saveOdooNames = function(o) {
  return processNamesRequest(o)
};

Answer №3

It occurred to me that I was mistakenly trying to save an array of objects into the inputs array without specifying the index, which resulted in "undefined" values being returned. Here is the corrected approach:

SOLUTION 1 :

$scope.saveOdooNames = function(o) {                    
    var data = [];
    for (var i = 0; i < o.length; i++) {                
        data.push({_id: o[i]._id, odoo_name: o[i].odoo_name});                
    }
    console.log(data);
    // $http post code 
};  

However, the above code retrieves all odoo_name fields even those that were not changed or modified. This led me to implement a second solution.

SOLUTION 2 :

I utilized underscore filter by directly calling my model without passing "o" as a parameter.

$scope.saveOdooNames = function () {          

    var o = _.filter(vm.localAttributes, function (x) {
        return x.odoo_name;
    });
    var data = [];
    for (var i = 0; i < o.length; i++) {                
        data.push({_id: o[i]._id, odoo_name: o[i].odoo_name});                
    }
    console.log(data);
    // $http post code
}

Both solutions are effective, but the one using filter allows me to utilize angular filters for the first solution.

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

Javascript data table pagination and custom attributes resulting in unexpected truncation of strings

Currently, I have implemented an Ajax functionality in my template to receive a JSON response and dynamically populate a datatable with the elements from that JSON: $('.bicam_tests').click(function(){ $.ajax({ type: 'GET', ...

Losing scope of "this" when accessing an Angular2 app through the window

My Angular2 app has exposed certain methods to code running outside of ng2. However, the issue arises when calling these methods outside of ng2 as the context of this is different compared to when called inside. Take a look at this link to see what exactl ...

The canvas grid is malfunctioning and failing to display correctly

My current code allows me to draw a grid on a canvas with multiple lines, but I'm encountering an issue when trying to render 25 or more lines - some of them don't appear on the canvas. This problem becomes more noticeable when there are 40 or mo ...

Tips for creating an option list on the fly

In need of help here! I have a dropdown list that needs to be dynamically populated using jQuery because the list contents are constantly changing. I initially got the code inspiration from a website, but it was built with a fixed number of items in mind. ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

What is the best way to eliminate the # symbol from a URL within a Vue.js application when utilizing a CDN

When constructing a vue.js application using CLI and vue-router, you can include mode: 'history' in the router to remove the hash from the URL. However, is there a way to eliminate the # from the URL when using Vue through a CDN? For instance, in ...

Execute a Python script with a JavaScript click event

I am looking for a way to run a Python script with just a click of a button on an HTML page and display the result on my page. Since this is a small project, I want to avoid learning more complex frameworks like Django even though I understand they would w ...

Using karma for angular to compile directives

I encountered a perplexing issue and now I'm feeling stuck. My main goal is to conduct tests on a list of directives within my project. These Directives have the following structure: angular.module('lessons', []).directive('uwTextare ...

What is the best way to ensure that text moves to the next line if it exceeds the boundaries of the parent div in either CSS or

I am looking to have the "remaining books count" and "remaining pens count text" automatically move to the next line below the numbers when they exceed two digits, causing an overflow in their parent div. Here is the code snippet I currently have: functi ...

The state remains unchanged when clicking on the div element

I am encountering an issue when trying to change the data attribute data-sort of a clicked DIV. Despite my efforts, I can only seem to get the value "DESC" each time. How can I successfully modify the data-sort attribute based on user interaction? jQuer ...

Show the percentage of completion on the progress bar while uploading with AJAX

I'm having trouble updating the current upload value on my progress bar in real-time. I know how to do it when the progress bar has stopped, but I can't get it to update continuously. xhr.upload.onprogress = function(e) { if (e.lengthComputa ...

Is there a way to switch on and off an ngrx action?

Here is a statement that triggers a load action to the store. The relevant effect will process the request and return the response items. However, my goal is to be able to control this action with a button. When I click on start, it should initiate dispa ...

Utilize ReactJS and AJAX to easily upload images

Having trouble with uploading an image through a form to a url/api. When I submit the form, I'm calling the handleImgUpload() method. The issue is that the request being sent is coming back empty. Seems like there might be a problem with new FormData ...

Angular: Unable to access values of non-existent data (reading '0')

I'm encountering an error when trying to import an excel file using the following code Angular Ag Grid Excel Import Cannot read properties of undefined (reading '0') I'm attempting to import a file named Book.csv, and wondering if thi ...

Adjusting the definition of a class method in TypeScript or JavaScript

In my code, I have a class defined as follows: class A { constructor() {} myMethod() { console.log('in my method'); } } I am looking to create a method that will take in a className and methodName like so: modifyClassMethod(cla ...

Wrap a HTML element with another element

Having an issue and uncertain if js can solve it. Let's assume there is a p Element. <p class="test> text text text </p> Can jquery transform the above statement into this. <div class="new_created"> <p class="test> text text ...

Python code malfunctioning only under a post request execution

My task involves executing a post request to initiate a child process for running my discord_bot.py script with the inclusion of a variable. The script runs smoothly when executed directly from the terminal; however, encountering crashes at a specific stag ...

Ways to retrieve the values from a numpy array employing an array that includes the index numbers I wish to retrieve

Let's say I have two numpy arrays. The first one, named idxes, includes the indices of elements that I want to extract from another array called arr. arr = ['a', 'b', 'c' ] idxes = [1, 2] // This is the desired result re ...

Analyze two sets of JSON data and compile a new JSON containing only the shared values

I am trying to generate two JSON arrays based on a shared property value from comparing two sets of JSON data. this.linkedParticipants =[ { "id": 3, "name": "Participant 2", "email": "<a href="/ ...

Tips for refreshing a nested state in React

Currently, I am facing an issue with updating a nested value in a React state. My goal is to update data that is deeply nested, specifically 3 levels deep. Let me provide you with the state structure that contains the data: const [companies, setCompanies ...