Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 558
Pham Minh Tan Avatar asked May 06 '15 04:05

Pham Minh Tan


2 Answers

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

like image 90
Michael Lorton Avatar answered Sep 27 '22 17:09

Michael Lorton


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>
like image 37
shaunhusain Avatar answered Sep 27 '22 17:09

shaunhusain