user3237500
user3237500

Reputation: 45

Dynamic variables in ng-model

Im new in Angular and I stared working in one project witch is using it for front end side. The thing is. I have a dropdown witch has values 1,2,3 etc... and when you select something in dropdown, depending on what you click. currentEntry variable is changing value and im filtering data value="{{entry['properties'][currentEntry]['password']}}". This works perfectly when I have simple input tag.

But when I do this:

<input type="password" name="pasword" ng-model="password" ng-change="addProperty(password,'password')" class="form-control" placeholder="Password" value="{{entry['properties'][currentEntry]['password']}}">

whats happening up there is that ,value properity is changing when i do inspect element in code but not on the client.

Than i realized that value is stored in ng-model, so I need to somehow create this models dinamicaly for example when I click on drop down item witch has value 1 ng-model should look like this ng-model="password1" etc...

I have this number stored in variable "currentEntry" so i tried to do something like this

<input type="password" name="pasword" ng-model="password{{currentEntry}}"......>

but I get syntax error

Token '{' is an unexpected token at column 9 of the expression [password{{currentEntry}}] starting at [{{currentEntry}}].

How to solve this?

Upvotes: 3

Views: 5957

Answers (1)

NicolasMoise
NicolasMoise

Reputation: 7279

You can't do dynamic variables like that in Javascript (this is not php). Instead use a function or an object.

Function

$scope.password = function(){
    //use $scope.currentEntry here
    return value;
}

and in your view

<input type="text" ng-model="password()"/>

Object

Another possibility would be this

<input type="text" ng-model="passwords[currentEntry]">

Where $scope.passwords is an object containing your passwords as such.

$scope.password= {1: 'a password', 2: 'another password'}

Also see Use dynamic variable names in JavaScript for more on dynamic variables in Javascript.

Upvotes: 3

Related Questions