How to send both model value and model name to a function in an AngularJS controller

$scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]

//Looking to pass model name and value of the model. Currently sending ngObject.MainObj.specificFormatObj

HTML

<select ng-model="ngObject.MainObj.specificFormatObj" ng-change="ngObject.MainObj.specificFormatObj">
    <option></option>
    <option ng-repeat="i in populateMap" value="{{i}}">{{i.name}}</option>

JS

// CONTROLLER CODE JSON parse object to get name and code GOT parsedObj
$scope.genericSetLookups=function (Obj) {  // Hoping to acquire the ngmodel string along with the value, currently only value is received
    Obj.code=parsedObj.code;
    Obj.name=parsedObj.name
};

Description: ngObject.MainObj.specificFormatObj

  • I aim to store lookup values in a specific way within my model, including both name and code. On the UI, I populate using ng-repeat, so when selecting a value, I can use i.name for display and set the value as i.code.
  • If I do that, ngObject.MainObj.specificFormatObj.name will be null, and the value will be set to ngObject.MainObj.specificFormatObj.code using ng-model. Therefore, I am specifying i as the value in ng-repeat instead of i.code or i.value. Now, in the map, I have pairs of code and name.
  • When passing it to a function and parsing it, I set the value in ngObject.MainObj.specificFormatObj.code=inputTofunc.code, and respectively for name. In this scenario, in ng-change, I am passing ngObject.MainObj.specificFormatObj.code, but I actually want to set i from the map to ngObject.MainObj.specificFormatObj before sending it to the function, also specifying the model string which would be "ngObject.MainObj.specificFormatObj".
  • So, for multiple lookups, I can write generic code where I can send the model name and model value as parameters to the function. The current approach may involve hardcoding values that I wish to set in the model in a specific format.

Answer №1

When passing the model name as a parameter, it is important to pass it as a string from html like this:

ng-change="genericSetLookups('ngObject.SomeObject.abc', ngObject.SomeObject.abc)"

Since the model name contains ".", direct usage of the name as the key in the controller is not possible. It is necessary to parse the model name. After some research, I have come up with a solution that should work.

Controller code:

$scope.genericSetLookups(modelName, value) {
    Object.setValueByString($scope, modelName, value);
}

Object.setValueByString = function(o, s, val) {
    s = s.replace(/\[(\w+)\]/g, '.$1');
    s = s.replace(/^\./, '');
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            if(i != n-1){
                o = o[k];
            } else {
                o[k] = val;
            }
        } else {
            return;
        }
    }
    return o;
}

Credit goes to @Alnitak for providing an answer here

Answer №2

I'm having trouble understanding your issue, and the comments didn't provide much clarity for me. To shed some light, I'll offer an example of how I typically handle a select box and the corresponding model.

In my approach, I iterate through the options using ng-options and display the selected option by inserting {{selected.name}} in the template. If you need to format the selected value or respond to changes, you can utilize ng-change.

Hopefully this explanation is useful to you.

You can view my JSFiddle here

Answer №3

I'm not exactly clear on what you're asking. If you're looking to store the code and name together in your model, this snippet of code might be helpful:

 <select ng-model="ngObject.MainObj.specificFormatObj" ng-options="(ppm.code + '-' + ppm.name) as ppm.name for ppm in populateMap">
 </select>

Check out this jsfiddle example

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

Sending Uint8Array buffer without any null bytes

I am attempting to transfer image data from the Jimp image object to Tesserract (OCR library) using a buffer: image.getBufferAsync('image/png').then((buffer) => { // Buffer here is <Buffer 12 34 56 ... const worker = new TesseractWorke ...

Incorporate AngularJS into jQuery plugins for enhanced functionality

My current project includes multiple jQuery plugins that I am looking to integrate into AngularJS. After some investigation, I discovered a way to create a custom directive for their initialization. However, my main concern now is figuring out how to man ...

Trouble arises when attempting to use JavaScript, JSP, and JSON in conjunction with

I am in the process of creating a client-server application where I send a request from the client to the server using a JSON object for registration. However, despite receiving a JSON response with an "OK" field as expected, the client keeps triggering th ...

Accumulating a result from elements.all.each in the latest version (4.0.1) of the protractor framework

I'm struggling to retrieve a date array from an each loop after it finishes iterating. Here's the provided code snippet for better understanding: this.Then(/^The details should match with Splunk data$/,function(callback){ var x=[]; pa ...

Is there a method available to define a custom auto-generated key when inserting an object into Firebase Realtime Database?

I've been working on pushing data to the firebase rtdb and I want to make sure I can easily access it from other places. Here's the code snippet that I'm using to add data to the rtdb: function addStudentHandler(studentData) { fetch( ...

I'm struggling to comprehend the purpose of this function. [From the Codecademy Contact List exercise]

Within the "for var x in friends" loop, the program aims to search each key within the friends object, such as bill and steve. Subsequently, with the condition "friends[x].firstName === name", the check is made if the first name matches the provided inpu ...

Easy-peasy AJAX bookmarking

One of my tasks involves displaying a list of items on a webpage with the use of PHP. I am looking to incorporate a straightforward AJAX toggle feature that will allow users to bookmark an item from the list while they are exploring. If the item's bo ...

Is it necessary to "debug" in JavaScript?

Is there a way in JavaScript or Visual Studio to identify if the code is being used in debug-mode? Is there an equivalent of "#if DEBUG" in C# for tracking debugging status? ...

Instructions on how to ensure that an AJAX call will only function when the user is logged in within a Rails application

My application allows users to save photos by clicking on them, but this feature is only available when the user is logged in. Strangely, even when a user is logged out, they can still click on a photo and save it because the show page is identical for bot ...

What is the best way to confirm if an element has focus?

As part of my testing, I am working to confirm that the focused element is properly set upon page load. Although it appears to be functioning correctly and I can verify this using the element explorer, the Jasmine matchers do not seem to detect this. Bel ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...

How can I turn off the ToggleButton?

Currently, I am utilizing a ToggleButtonGroup in my task list to categorize my input as either today, tomorrow, this week, or no date. If none of the buttons are toggled, the tasks will be placed under 'no date', otherwise they will fall into one ...

What are the benefits of keeping synchronous state in the Redux store?

Is it necessary to store non-async state in the Redux store? For instance, when dealing with a modal that simply shows or hides, is it worth the extra work to toggle it within the store? Wouldn't it be simpler to just keep it as local state in the Rea ...

The Forward and Back Buttons respond based on the current position of the caret

Exploring the concept of a Keypad-Login. I am trying to create Back and Forward buttons. However, the back and forward buttons are currently inserting the letters at the end of the input value instead of at the caret position. The input field is disabled, ...

Executing usemin and useminPrepare on various targets is made possible by Grunt

According to the usemin issues, it seems that the latest version of usemin and useminPrepare now support multiple targets: Updates related to multiple targets in useminPrepare: pull#162 pull#206 New features for usemin support: Multiple targets A ...

What is the best way to replace a regular expression in JavaScript?

I've recently been exploring the functionalities of MathJax, a Javascript library that enables the use of LaTex and similar mathematical markup languages within HTML. However, when attempting to incorporate it into my Javascript code, I encountered so ...

What is the best way to properly format the retrieved JSON string using Ext JS?

After receiving the JSON data shown below, I need to change the formatting of the string values in the 'code' field. For example, 'TOTALPENDING' should display as "Pending Bonus" and 'TOTALLEFT' as "Current Bonus". How can I m ...

Node.js: Error - Module 'html' not found

Currently, I am utilizing Node.js and attempting to exclusively serve HTML files without any Jade or EJS engines. Below is the code for my entry point (index.js): var express = require('express'); var bodyParser = require('body-parser&apo ...

Generating personalized MongoDB collections for individual users - A step-by-step guide

My query is more about the procedure rather than a specific coding issue. I am working on a node application and using DHTMLX calendar. What I aim for is to have each user with their own set of events on their individual calendar. Currently, the implement ...

Having issues with the background-image style not displaying correctly in the header of an

Trying to update the "background-image:" of a CSS class upon button click. JQuery: $(function() { $('button').on('click', function() { $('.masthead2').css('background-image', 'url("../img/whitehead ...