"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

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...

Create functionality to toggle the visibility of a group of elements within a

I am currently working on a way to toggle the visibility of multiple divs within a group so that only one div is displayed at a time. While I could achieve this using the ng-show directive, I am looking for a more versatile solution. Here's an exampl ...

Ways to host static content in ExpressJS for specific directories and exclude others

I need to configure my ExpressJS server to serve static files from specific paths only, excluding others. For example, I want to serve static files from all paths except /files where I only need to manipulate a file on the server. Currently, my code looks ...

Error: The class constructor [] must be called with the 'new' keyword when creating instances in a Vite project

I encountered an issue in my small Vue 3 project set up with Vite where I received the error message Class constructor XX cannot be invoked without 'new'. After researching online, it seems that this problem typically arises when a transpiled cla ...

What is the best method for binding variables in Vue.JS using moustache syntax and passing parameters to them?

If I have an HTML structure like this: <div> {{ CUSTOM_MESSAGE }} </div> And in my data: data() { return { CUSTOM_MESSAGE: 'Hey there! This message is for {{name}} from {{location}}' } } Is there a way to dynamically p ...

Generate unique IDP SAML replies

Currently, I am working on creating unit test cases for validating SAML responses. To achieve this, I am seeking guidance on generating multiple SAML responses in XML format using the necessary certificates and private keys. Are there any Node.js librari ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Error always appears when using addMethod in jQuery validator

$.validator.addMethod("validateEmail", function() { $.ajax({ type: "POST", url: "/user/check_email", data: { email: $( "#email" ).val() }, success: function(data) { console.log(dat ...

Remove any posts that have a date earlier than the current day

Currently, I am working on a website showcasing events organized by my friend's music label. However, I have run into an issue while attempting to implement an "archiving automation". The code I have tried below is not functioning as expected, as my " ...

Discover identical JSON elements in 2 JSON arrays using JavaScript and add CSS styles to the corresponding items within a UL list

In order to manipulate JSON data using JavaScript, I am required to create an HTML UL list of tags based on a JSON array of Tag items. Furthermore, there is a second set of Tags in another JSON data-set that needs to be compared with the first Tag JSON da ...

Server side processes automatically converting boolean parameters in Axios get requests to strings

My code involves a JSON object being passed as parameters to the Axios GET API. Here is the JSON object: obj = { name: "device" value: true, } The Axios GET request is made with the above object like this - tableFilter = (obj) => { ...

What is the process for generating an HTTP response that results in a pipe error being thrown

In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database. Recently, I discovered that the pipe ...

Error: Material UI search bar doesn't refresh interface

I implemented Material UI's auto complete component to create a dynamic select input that can be searched. The component is fed options in the form of an array consisting of strings representing all possible choices. <Grid item xs = {props.xs} cla ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Performing a $lookup operation across various collections for a nested output

I have multiple collections and I've utilized the separate collection & foreign key approach. Now, I'm looking to combine these collections to create nested collections. Take a look at my collection schemas: const SurveySchema = new Schema({ _id ...

What is the best way to change a date-containing string into a Json object?

I need to convert a string into a JSON Object using JavaScript. However, when I do so, the date in the original string gets completely changed. Here is the string I am working with: var JsonData=[[2013-02-27,787],[2013-02-26,131],[2013-02-02,0],[2013-01- ...

Once the Ajax request is finished, the cookie deletion function ceases to function

When the website loads, a cookie is generated using PHP before any other content or headers are sent. This is done with the following code: $steam_login_verify = SteamSignIn::validate(); if(isset($_COOKIE['userid'])) { //work with cookie va ...

Having trouble finding module: Unable to locate 'fs' - yet another hurdle with NextJS

Trying to access a JSON file located one directory above the NextJS application directory can be tricky. In a standard JavaScript setup, you might use the following code: var fs = require('fs'); var data = JSON.parse(fs.readFileSync(directory_pat ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...