角UI选择二,为什么NG-模型中获取设置为JSON字符串? [英] Angular UI Select2, why does ng-model get set as JSON string?

查看:145
本文介绍了角UI选择二,为什么NG-模型中获取设置为JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用了棱角分明的UI的SELECT2一个相当简单的下拉列表。它是由数据坐在我的控制器范围的静态数组的支持。在我的控制器我有一个被调用的下拉的NG-变化,这样我可以执行一些操作的值更改时功能。

I'm using angular-ui's select2 for a fairly simple dropdown. It's backed by a static array of data sitting on my controller's scope. In my controller I have a function that gets called on ng-change of the dropdown so that I can perform some actions when the value changes.

不过,我发现的是,NG-模型的属性,都会设置一个JSON字符串,而不是一个实际的JavaScript对象,这使得它不可能使用点符号抢特性关闭该模式。

However, what I'm finding is that the ng-model's property gets set as a JSON string rather than an actual javascript object, which makes it impossible to use dot notation to grab properties off of that model.

下面是处理下拉的价值功能得到改变:

Here's the function that handles the value of the dropdown getting changed:

$scope.roleTypeChanged = function() {
  //fine:
  console.log('selectedType is: ', $scope.adminModel.selectedType);

  // this ends up being undefined because $scope.adminModel.selectedType is a 
  // JSON string, rather than a js object:
  console.log('selectedType.typeCode is: ', $scope.adminModel.selectedType.typeCode);
}

下面是我完整的例子的plunker: http://plnkr.co/edit/G39iZC4f7QH05VctY8zG

Here's a plunker of my full example: http://plnkr.co/edit/G39iZC4f7QH05VctY8zG

我从来没有见过一个绑定到NG-模型的属性做到这一点之前,但我也相当新的角所以它可能是我只是在这里做得不对。我当然可以这样做$ .parseJSON()将JSON字符串转换回一个对象,但我宁愿没有,除非我不得不这样做。
感谢您的帮助!

I've never seen a property that's bound to ng-model do this before, however I'm also fairly new to Angular so it's likely that I'm just doing something wrong here. I can certainly do something like $.parseJSON() to convert the JSON string back to an object, but I'd rather not unless I have to. Thanks for any help!

推荐答案

您需要的,如果你想有对象的值上使用您的选择NG选项。实际创建使用NG重复的选项自己只会让你有各种选项字符串值:

You need to use ng-options on your select if you want to have object values. Actually creating the options yourself using an ng-repeat will only allow you to have string values for the various options:

<select ui-select2
    ng-model="adminModel.selectedType"
    ng-change="roleTypeChanged()"
    data-placeholder="Select Role Type" ng-options="type.displayName for type in adminModel.roleTypes">
  <option value=""></option>
</select>

http://plnkr.co/edit/UydBai3Iy9GQg6KphhN5?p=$p$ PVIEW

这篇关于角UI选择二,为什么NG-模型中获取设置为JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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