"Learn the process of setting a variable in ng-model within an input field based on a specific condition

I need to dynamically assign an ng-model variable based on a condition. For instance:

<input type="text" ng-model="item.model[multilang]" >

The $scope.multilang variable can be set to either "ENG", "JP" (languages) or false. So, when multilang = "ENG" and the user types in "Hello" into the input field, the result will be:

item.model = {ENG: "Hello"}

The issue arises when $scope.multilang is set to false. In such cases, I want the result to simply be:

item.model = "Hello"

I am struggling to figure out how to achieve this scenario. One potential solution that comes to mind is to change the ng-model attribute based on the value of $scope.multilang - so if it's false, the ng-model would become ng-model="item.model". However, I'm not sure how to implement this.

EDITED I have come up with one possible solution:

<input ng-if="multilang" type="text" ng-model="item.model[multilang]" >
<input ng-if="!multilang" type="text" ng-model="item.model" >

Is there a better way to achieve this functionality?

-----plnkr example-----

Answer №1

Angular offers a high level of flexibility and power as a framework. Utilizing custom directives along with ngModel's getter/setter option can greatly enhance your development process.

If you choose to use a directive without ngModel's getter/setter, the code may look like this:

<input type="text" 
       ng-model="val" 
       multilang="multilang" 
       multilang-model="item.model">

The corresponding directive code would be:

.directive('multilang', [function(){

    return {

      restrict: "A",

      require: "ngModel",

      scope: {
        multilang: "=",
        multilangModel: "="
      },

      link: function(scope, element, attr, ngModel){

        ngModel.$viewChangeListeners.push(function()){

          var value = ngModel.$modelValue;

          if(scope.multilang !== false) {

            if(typeof scope.multilangModel == 'undefined')
              scope.multilangModel = Object.create(null)

            scope.multilangModel[scope.multilang] = value

          }

          else {

             scope.multilangModel = value

          }
        })
      }
    }
 }])

--check out the updated plunkr demo--

If opting for ngModel's getter/setter approach, you could modify the input like so:

<input type="text" 
       ng-model="val" 
       multilang="multilang" 
       multilang-model="item.model" 
       ng-model-options="{ getterSetter: true }">

The associated directive code for this scenario:

.directive('multilang', [function(){

    return {

      restrict: "A",

      scope: {
        multilang: "=",
        multilangModel: "=",
        val: "=ngModel"
      },

      link: function(scope, element, attr){

        scope.val = function(newValue) {

          if(scope.multilang !== false) {

            if(typeof scope.multilangModel == 'undefined')
              scope.multilangModel = Object.create(null)                

            return arguments.length ? (scope.multilangModel[scope.multilang] = newValue) : scope.multilangModel[scope.multilang];

          }

          else {

             return arguments.length ? (scope.multilangModel = newValue) : scope.multilangModel;

          }
        }
      }
    }
 }])

--see the enhanced plunkr example here--

In my view, the second method is preferable. It enables two-way binding with item.model, updating the input value when changes are made to item.model elsewhere in the codebase.

Answer №2

Give this a shot:

<input ng-show="multilang" type="text" ng-model="item.model[multilang]" >
<input ng-hide="multilang" type="text" ng-model="item.model" >

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 issue of calling the child window function from the parent window upon clicking does not seem to be functioning properly on Safari and Chrome

I'm attempting to invoke the function of a child window from the parent window when a click event occurs. Strangely, this code works in Firefox but not in Safari or Chrome. Here is the code snippet I am using: var iframeElem = document.getElementById( ...

Is it possible to store data from a form directly into a MongoDB database?

I am looking to store data collected from an HTML form into a MongoDB database. Below is the code I am using: <!DOCTYPE html> <html> <head> <title>Getting Started with Node and MongoDB</title> </head> <body> ...

Divide a JavaScript project into multiple packages using either webpack or npm

I am embarking on the development of an application that needs to be compatible with Windows (PC), Android, and iOS. To achieve this, I plan to use Electron for Windows and React Native for mobile platforms. Both applications will be built using React and ...

Implementing dynamic class bindings with Vue.js using v-for

I am currently using a v-for loop in Vue.js to create a list of items populated with data from an API. Here is an example of the items array: items: [ { foo: 'something', number: 60 }, { foo: 'anything', ...

Implementing Ajax calls to dynamically update Datatable results

Currently integrating Datatables.js with an ajax call for data retrieval. The json response I'm receiving is as follows: "success":true,"message":"","items":[{"id":"1","ip_address":"127.0.0.1","email... My data is stored within the data.items array ...

Retrieve the image and insert it using an img tag

Working on a project, I want to include Instagram profile pictures by embedding them. Although I have the image URL, I am struggling to integrate it into my HTML page. Take a look at this sample: This provided link displays the Instagram profile picture. ...

Eradicate white space in a JavaScript code

Calling all JS programmers! Here's a challenge for you, check out this demo: https://codepen.io/gschier/pen/jkivt I'm looking to tweak 'The pen is simple.' to be 'The pen issimple.' by removing the extra space after 'is& ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

Implementing the firebase-admin SDK module into an AngularJS project

How can I integrate firebase-admin into my AngularJS project? Any assistance on this matter would be greatly appreciated! Thank you. ...

Arrange an asynchronous function in Node.js

I have been attempting to set up a schedule for an asynchronous function (with async/await return type) to run every two minutes. Although I have tried using the generic setInterval, as well as various node modules such as node-schedule, cron, node-cron, ...

Launching a web application directly from a USB drive

Exploring the world of Javascript frameworks and nodejs, I recently encountered a unique requirement that got me thinking about their practical application. The requirements are as follows: --I need to create a lightweight website that can be run from a U ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

Fixing the "Package Manager Not Found" Issue when Deploying a Next.js Project on Vercel

Having created a website using Next.js and aiming to deploy it on Vercel, I encountered an error during the deployment process despite meticulously following the configuration steps. The error message displayed was: "Unable to determine package manage ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

Node.js encountering difficulty extracting JSON data

Within this JSON object, the Variable SNS holds valuable information that I need to extract and save in a new variable. `const sns = event.Records[0].Sns.Message;` The specific values I aim to retrieve are Trigger.Namespace, Trigger.Dimensions.value, an ...

The TypeScript Promise error codes TS2304 and TS2529 are causing confusion among

I came across the code below: function asyncTask(): Promise<string> { return new Promise<string>(resolve => resolve); } This code resulted in the following error: TS2304: cannot find name 'Promise' To address this issue, ...

Transforming the MUI CircularProgress into a half circle shape

After utilizing CirculaProgress, I was able to achieve the following: Is there a simple method to transform it into a semicircle like shown here? ...

Retrieve the value of a field from a Formik form integrated with Material UI

I've been working on a way to disable a checkbox group depending on the selected value of a radio group. I took inspiration from the technique outlined in the final section of the Formik tutorial. Using React context has definitely helped clean up the ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...