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?

0

3 Answers 3

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...

Sign up to request clarification or add additional context in comments.

4 Comments

Wow. You know Vietnamese? :)
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.
Well. Nice to meet you. Thank you again :). I hope, i can meet you in real life. :)
What if it's a deep object?
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.