javascript AngularJS:ng-model 中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30067512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:36:41  来源:igfitidea点击:

AngularJS : Variables in ng-model

javascriptangularjsangularjs-ng-repeatangularjs-ng-model

提问by Pham Minh Tan

I have a loop ng-repeat

我有一个循环 ng-repeat

<div ng-repeat="data in datas">
Name: {{data.name}} <input type="text" ng-model="age">
</div>

I want $scope.agebecome 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?

我想$scope.age成为$scope.age_data.name. 例如:$scope.age_Tan$scope.age_Jim... 所以我试过了,ng-model="age_{{data.name}}"但它出错了。如何解决这个问题?

回答by Malvolio

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

应该管用...

回答by shaunhusain

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>

回答by Yang You

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>