How to create Dynamic ng-model in Angular

拜拜、爱过 提交于 2019-12-02 06:12:06

问题


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 %>">

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

I want to achive teller1, teller2 etc..

Thanks!


回答1:


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 :)



来源:https://stackoverflow.com/questions/32517046/how-to-create-dynamic-ng-model-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!