AngularJS : Variables in ng-model
Asked Answered
A

3

5

I have a loop ng-repeat

<div ng-repeat="data in datas">
Name: {{data.name}} <input type="text" ng-model="age">
</div>

I want $scope.age become to $scope.age_data.name. Eg: $scope.age_Tan, $scope.age_Jim... So i have tried ng-model="age_{{data.name}}" but it make error. How to solve this?

Aime answered 6/5, 2015 at 4:24 Comment(0)
P
16

The "right" way to do this is to, in the controller, do this:

$scope.ages = {};

Then in the template:

Name: {{data.name}} <input type="text" ng-model="ages[data.name]">

Should work...

Pathway answered 6/5, 2015 at 4:35 Comment(4)
Wow. You know Vietnamese? :)Aime
Enough Vietnamese to order phở at any roadside stand along Route 1, but not much more. I hope to spend a few months in Danang at some point and really learn the language.Pathway
Well. Nice to meet you. Thank you again :). I hope, i can meet you in real life. :)Aime
What if it's a deep object?Mauve
P
1

What you show here won't work exactly here's a couple of options

angular.module('myApp', [])
  .controller('MyCtrl', function() {
    var vm = this;
    vm.datas = [{
      name: 'thing1'
    }, {
      name: 'thing2'
    }, {
      name: 'thing3'
    }];
  })
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>

<body ng-controller="MyCtrl as myCtrl">
  Option 1
  <div ng-repeat="data in myCtrl.datas">
    <input type="text" ng-model="data.age" />
  </div>

  <br/>
  <br/>Option 2
  <div ng-repeat="data in myCtrl.datas">
    <input type="text" ng-model="myCtrl.age[data.name]" />
  </div>
  <pre>{{myCtrl|json}}</pre>
</body>

</html>
Pacificas answered 6/5, 2015 at 4:35 Comment(0)
F
0

I am not sure why you want to keep age of a person in another object/container. Here is the solution which may help you rethink you design.

$scope.people= [
  {name: 'Tan', age: 20},
  {name: 'Jim', age: 21}
];

<div ng-repeat="person in people">
Name: {{person.name}} <input type="text" ng-model="person.age">
</div>
Future answered 6/5, 2015 at 5:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.