最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS : Variables in ng-model - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Sep 29, 2015 at 11:25 John Slegers 47.1k23 gold badges204 silver badges173 bronze badges asked May 6, 2015 at 4:24 Pham Minh TanPham Minh Tan 2,0967 gold badges27 silver badges39 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 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...

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>

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>
发布评论

评论列表(0)

  1. 暂无评论