我们正在尝试根据客户选择的联系人显示客户的信息。当我们使用 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': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52223b2828333f332b303712353f333b3e7c313d3f" rel="noreferrer noopener nofollow">[email protected]</a>',
'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
之外,还有什么好的方法可以做到这一点吗?提前致谢!
最佳答案
问题是您正在使用value="{{contact}}"
这会导致 Angular 将对象打印为 JSON 字符串。
因此,当从选择列表中的 ng-model 分配值时,变量会被分配一个字符串值,即
"{"CntctKey":"331518","Name":"Cheryl","Phone":"55555115","PrimaryCntct":"0"}"
,而不是对象本身。
这就是为什么在您的 plnkr 中,具有 ng-model="contactPerson1.CntctKey"
的第二个字段没有值,因为对于字符串,此属性未定义。
要解决此问题,您只需使用数组元素的索引来引用该对象即可。
您可以通过在联系人中使用 ng-repeat 的键映射 (contactKey, contact) 来访问此索引
。
或者,如果您只是将所有内容存储在平面连续数组中(如示例中所示),则只需使用 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
关于angularjs - 从 Select 更新 ngmodel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25171578/