AngularJS : Variables in ng-model

18,334

Solution 1

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

Solution 2

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>

Share:
18,334
Pham Minh Tan
Author by

Pham Minh Tan

I'm a web developer based in Ho Chi Minh City, Viet Nam. Generally, I focused web developer front-end, website back-end, and design. However, this discipline I like to use my web knowledge on web and software solutions. Web design, application design and more. I have 4 years of experience as a software engineer and working on outsourcing company, and I'm ready for your project. I love working with people believed that good thing needs passions, time and attentive.

Updated on June 07, 2022

Comments

  • Pham Minh Tan
    Pham Minh Tan almost 2 years

    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?

  • Pham Minh Tan
    Pham Minh Tan about 9 years
    Wow. You know Vietnamese? :)
  • Michael Lorton
    Michael Lorton about 9 years
    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.
  • Pham Minh Tan
    Pham Minh Tan about 9 years
    Well. Nice to meet you. Thank you again :). I hope, i can meet you in real life. :)
  • Ivan Rubinson
    Ivan Rubinson almost 6 years
    What if it's a deep object?