Angular UI Select2,为什么ng-model被设置为JSON字符串?

时间:2013-07-08 20:37:27

标签: angularjs jquery-select2 angular-ui

我正在使用angular-ui的select2进行相当简单的下拉菜单。它由我控制器范围内的静态数据阵列支持。在我的控制器中,我有一个函数,可以在下拉列表的ng-change上调用,以便在值发生变化时执行一些操作。

然而,我发现的是,ng-model的属性被设置为JSON字符串而不是实际的javascript对象,这使得无法使用点表示法从该模型中获取属性。

这是处理下拉列表更改值的函数:

$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);
}

以下是我的完整示例的摘要:http://plnkr.co/edit/G39iZC4f7QH05VctY8zG

我以前从未见过一个与ng-model绑定的属性,但是我对Angular也很新,所以我可能在这里做错了。我当然可以像$ .parseJSON()那样将JSON字符串转换回对象,但除非必须,否则我宁愿不这样做。 谢谢你的帮助!

2 个答案:

答案 0 :(得分:5)

如果您想拥有对象值,则需要在select上使用ng-options。实际上,使用ng-repeat自己创建选项只允许您为各种选项提供字符串值:

<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=preview

答案 1 :(得分:2)

谢谢卡尔! 我已经用这个努力了一天

作为其他人遇到类似问题的说明, 当使用在控制器/指令中无法访问和定义的ng模型时,我就这样解决了它。

// country.Model具有代码和名称节点

* HTML *

 <select 
name="country" data-ng-model="country.Model"  
    data-ui-select2=""  
    data-ng-change="countryChanged(country.Model)"  <!--only for test, log to console-->
    data-ng-options="country as CodeAndName(country) for country in countries"
    data-placeholder="{{placeholderText(country.Model, '- - Select Country - -')}}" >
    <option value=""></option>
</select>  

* JS *

 function controller($scope, $q, $location, $routeParams) {

    $scope.countryChanged = function(item) { // for test                
      console.log('selectedType is: ', item);
    };

    //returns the item or the text if no item is selected
    $scope.placeholderText = function (item, text){ 
        if (item == undefined)
            return text;
        return $scope.CodeAndName(item);
    };

    // returns a string for code and name of the item, used to set the placeholder text
    $scope.CodeAndName = function (item) { 
        if (item == undefined)
            return '';
        return item.Code + ' - ' + item.Name;
    };