Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - bind ng-model to a variable which name is stored inside another variable

Tags:

People also ask

What is [( ngModel )]?

The ngModel directive is a directive that is used to bind the values of the HTML controls (input, select, and textarea) or any custom form controls, and stores the required user value in a variable and we can use that variable whenever we require that value. It also is used during form validations.

Can ngModel have multiple values?

The solution is ng-bind-template, it can bind more than one {{}} expression, so it can show more than a single value that was declared in the Script function.

How do you bind an NG model?

Use the ngModel selector to activate it. It accepts a domain model as an optional Input . If you have a one-way binding to ngModel with [] syntax, changing the domain model's value in the component class sets the value in the view.

Can we use model ng instead of NG model?

There is no difference between them. I can't find any occurrence of ng-model in the page you linked to.


I'm trying to bind the value of an input field to a variable. I don't know the name of this variable a priori; it is stored in another variable.

This is the html:

<body ng-controller="stageController">
    <form name="myForm" novalidate="">
        <input type="text" name="myText" ng-model="model" />
    </form>
</body>

and this is the controller:

function stageController($scope) {
    $scope.model = 'realModel'; // contains the name of the variable that i would bind to the field 
    $scope.realModel = 'initial value of the field';
}

I made also a fiddle.

This doesn't work because currently the binding is between the input field and the model variable. Instead I would bind the input field to the variable which name is stored inside the $scope.model variable (in this case realModel).

Is it possible? How?