如何在Angular中创建动态ng模型 [英] How to create Dynamic ng-model in Angular

查看:56
本文介绍了如何在Angular中创建动态ng模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Angular中创建动态ng模型?我尝试过,但是我想让它运行起来很困难.我得到的是不确定的.这是我的代码.

How can I create dynamic ng-models in Angular? I tried but I think I'm having a hard time getting it to run. All I get is undefined. Here's my code.

<input type="text" class="form-control input-sm" ng model="teller[value.teller_id]" value="<% value.mac_address %>">

我打算拥有一个具有相同名称但只能按数字更改的ng模型.我有一个可容纳1-4的数字的对象.这是value.teller_id.我想将其附加到ng-model中,如teller1,teller2,teller3(teller [value.teller_id]等.)由ng-repeat循环播放,我没有任何问题,但可以创建动态ng-model和更改数字将产生不确定的结果.

I am planning to have a ng-model that has the same name but only changes by number. I have an object that holds the number from 1-4. which is value.teller_id. I want to append it to the ng-model as teller1,teller2,teller3 (teller[value.teller_id] etc.. It is looped by ng-repeat which I don't have any problem but rather creating the dynamic ng-model and changing the number will yield undefine.

 ng model="teller[value.teller_id]" <---- doesn't work

我想达到出纳员1,出纳员2等.

I want to achive teller1, teller2 etc..

谢谢!

推荐答案

是.我们可以动态生成ng-model名称.

Yes. We can generate ng-model name dynamically.

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.teller = {};
  $scope.name = [{
    "id":1
  },{
    "id":2
  }]
});

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28/angular.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div ng-repeat="x in name">
      <input type="text" ng-model="teller[x.id]" />
    </div>
    <pre>{{teller | json}}</pre>
  </body>

</html>

希望它适合您的情况:)

Hope it works for your case :)

这篇关于如何在Angular中创建动态ng模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆