Extract the ng-model name from the scope variable in Angular

Is there a way to accomplish this?

ng-model="{{att.myModel}}"

I have an array called AllSmallText which contains items. I want to create a form using ng-repeat on AllSmallText and set the ng-model value to be myModel, which is one of the item fields.

<div ng-repeat="att in AllSmallText" class="col-xs-6 col-md-6">
    <input class="form-control" name="firstname" placeholder="{{att.title}}" type="text"
      ng-model="{{att.myModel}}"
      required autofocus />
  </div>

Thank you

Answer №1

To avoid using curly braces, simply utilize ng-model='attr.myModel'.

New and Improved Answer

ngModel will attempt to connect with the specified property by evaluating the expression within the current scope. Should this property not exist in the scope already, it will be generated implicitly and appended to the scope.

Create a fresh scope,

$scope.newScope = {};

Then implement

ng-model="newScope[attr.myModel]"
, which generates a new scope property such as $scope.newScope.example

We trust this explanation proves beneficial.

Answer №2

When searching for something in this manner, try employing the subsequent syntax:

Rather than utilizing ng-model="{{att.myModel}}", opt for ng-model="[att.myModel]"

Answer №3

If you're looking for a different approach, one way to do it is by incorporating the ng-model directive through another directive.

You can create an add-model directive in your HTML:

<input type="text" add-model="{{myModel}}" />

Then, within the directive, you can include the ng-model functionality:

myApp.directive('addModel', function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ctrl) {
            var model = attrs.addModel;
            element.attr('ng-model',  model);
            element.removeAttr('add-model');  // prevent infinite loop
            $compile(element)(scope);
        }
    };
});

Here's a working example on Fiddle: http://jsfiddle.net/oligustafsson/wuqqxtqu/

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

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Displaying an image based on user input

I'm attempting to display an image using JavaScript after a user completes an input field. I've managed to show the URL when using an input type="text," but when I attempt to change it to an img tag, it returns [object Object]. Is this achievable ...

The jQuery included does not function properly in production mode and results in an error stating that it is not a function

After placing the jquery.placeholder.js file in the assets/javascripts folder, I successfully applied the function in my coffeescript file and it worked perfectly. $(document).ready -> $('input, textarea').placeholder(); However, when swit ...

Header vanishes while using a JavaScript function to search through an HTML table

I'm facing an issue with a search function in a php script. The search function, written in javascript, is designed to sift through the table below and extract matching content as the user inputs text into the search field. It looks specifically withi ...

typescript in conjunction with nested destructuring

ES6 has definitely made coding more efficient by reducing the number of lines, but relying solely on typescript for everything may not be the best approach. If I were to implement type checking for arguments that have been destructed multiple levels deep, ...

Creating a navbar that sticks to the top of the page

I've been working on some code to create a sticky navbar that remains fixed as I scroll down, but unfortunately, it's not working. I suspect the issue might lie in the CSS, as the HTML and javascript seem fine. Interestingly, this same code has w ...

Angular Object Error: Unhandled Exception

As someone who is new to Angular, I am still trying to grasp how it functions. However, I have encountered an issue early on that is causing the below code to produce an "Uncaught Object" error in the console and disrupt Angular functionality. It seems t ...

Validating Web API tokens in AngularJS: A step-by-step guide

Currently, I am focused on AngularJS Authentication and retrieving tokens from a web API. During the route change event, my goal is to validate whether the generated token is valid or not. If it is indeed valid, I aim to redirect to a different route; howe ...

Show a particular attribute from an array

My goal is to create a function that displays only minivans from an array of cars when a button is pressed. However, I'm having trouble getting anything to display when the button is clicked, even though there are no errors in the program. Any advice ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

What is the best way to pause and wait for the user's click event in testing-library React until the state is updated?

Check out this link for the issue in codesandbox The tests in src/tests/App.test.js on codesandbox fail due to timing issues with state update after a click event (line 21). Uncommenting the function with await on line 21 can resolve this issue. What is t ...

React: image appearing in DOM but failing to render on screen

As I work on developing a web application using React, my focus is on creating cards that consist of header text and an image. However, I have encountered a problem with displaying the image properly. When I import the image and attempt to use it in my co ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Securely store passwords in JavaScript for future use

We are in the process of creating a web application that requires decrypting data stored on our server using the user's password. Our objective is to avoid repeatedly asking the user for their password, so we are considering storing the password in a ...

JavaScript for beginners: show a specified amount of search results and insert a loading indicator at the end

Currently, I have a website that retrieves data from my database using a PHP query. However, the issue I am facing is that there are over 300 entries in my database, resulting in an excessively long displayed page. My main question: How can I restrict ...

Encountering a TypeError with react-rte in Next.js: r.getEditorState is not a valid function

In my Next.js project, I am using a React RTE component. It is displaying correctly, but when I navigate to another component and then return using the browser's back button, I encounter the following error: Unhandled Runtime Error TypeError: r.getEd ...

Integrating various object properties in Angular's select ng-options: A comprehensive guide

I need to merge text and number properties from JSON to display as select options values by default. The expected output should be: 000.000.0001 - Chicago HTML: <!doctype html> <html ng-app="plunker" > <head> <meta charset="utf-8"& ...

Is it feasible to develop a functional computer interface using threejs?

Is it feasible to integrate a window into threejs that could facilitate the use of standard desktop applications (such as code editors) within the virtual scene? Please note: This is being implemented within a custom application or a node-webkit environme ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

AngularJS Date Selection with UI Bootstrap Tool

Just starting out with AngularJS and looking to add a datepicker to my project. I'm using angular.min.js version AngularJS v1.5.0-rc.1 ui-bootstrap-tpls-0.12.0.js version 0.12.0. There are so many examples online that it's confusing. How do I go ...