从Select更新ngmodel

时间:2014-08-06 22:50:56

标签: angularjs angular-ngmodel

我们会尝试根据客户选择的联系人显示客户的信息。当我们使用ng-options时,它按预期工作。但是,我们使用Ui.Select2和" ui-select2与。"不兼容。所以我们被迫使用ng-repeat,它没有按预期工作。

JS:

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

app.controller('Ctrl', function($scope){
  $scope.contacts = 
  [  { 
    'CntctKey': '331518',
    'Name': 'Cheryl',
    'Phone': '55555115',
    'PrimaryCntct': '0'
     } ,  
    { 
    'CntctKey': '118431',
    'EmailAddr': 'pizzamaybe@gmail.com',
    'Name': "Stephanie Pizza",
    'Phone': '555552255',
    'PrimaryCntct': '1'
 }  ];

});

HTML

  <h3>With ng-options</h3>
      <select ng-model="contactedPerson" ng-options="contact.Name for contact in contacts"></select>
      <input ng-model="contactedPerson.Phone"/>
      <input ng-model="contactedPerson.CntctKey"/>
      <br>
      <h3>With ng-repeat</h3>
      <select ng-model="contactPerson1" >
        <option ng-repeat="contact in contacts" value="{{contact}}">{{contact.Name}}</option>
      </select>
      <input ng-model="contactPerson1"/>
      <input ng-model="contactPerson1.Cntctkey"/>

http://plnkr.co/edit/9D9LTCnBOGAo2ftA1jbU

您可以看到ng-repeat它会显示该对象,但我们无法再将其钻入其中。

除了使用ng-options之外,有没有其他方法可以做到这一点?提前谢谢!

1 个答案:

答案 0 :(得分:4)

问题是您使用的是value="{{contact}}"

这会导致angular将对象打印为JSON字符串。

因此,当从选择列表中的ng-模型分配值时,为变量分配字符串值,即
"{"CntctKey":"331518","Name":"Cheryl","Phone":"55555115","PrimaryCntct":"0"}",而不是对象本身。

这就是为什么在你的plnkr中,你的第二个字段ng-model="contactPerson1.CntctKey"没有值,因为对于一个字符串,这个属性是未定义的。

要解决此问题,您只需使用数组元素的索引来引用该对象即可 您可以使用ng-repeat的键映射(contactKey, contact) in contacts来访问此索引。

或者,如果您只是将所有内容存储在一个平坦的连续数组中(如示例中所示),只需使用ng-repeat的$index变量。

<select ng-model="contactPerson1Index" >
    <option ng-repeat="contact in contacts" value="{{$index}}">{{contact.Name}}</option>
</select>
<input ng-model="contacts[contactPerson1Index].Phone"/>
<input ng-model="contacts[contactPerson1Index].CntctKey"/>

请参阅更新的plnkr:http://plnkr.co/edit/4thQmsZamN3tt0xpscj9

有关键映射和ng-repeats内部变量的更多信息,请参阅:https://docs.angularjs.org/api/ng/directive/ngRepeat

相关问题