Pham Minh Tan
Pham Minh Tan

Reputation: 2096

AngularJS : Variables in ng-model

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?

Upvotes: 5

Views: 19245

Answers (3)

Yang You
Yang You

Reputation: 2668

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>

Upvotes: 0

Michael Lorton
Michael Lorton

Reputation: 44406

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

Upvotes: 16

shaunhusain
shaunhusain

Reputation: 19748

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>

Upvotes: 1

Related Questions