如何创建角度ui-select指令包装器,它将所选项的属性绑定到模型

时间:2014-10-23 09:32:18

标签: angularjs-directive angular-ui ui-select2

我正在尝试创建angular指令,它是ui-select指令之上的包装器。我的目标是为指令提供一个包含项目和模型的列表,该模型将与所选项目的特定属性同步。我的指令有5个属性:

ng-model - to specify the model,
items - to specify the list of items,
display-prop - the name of the property which will be used inside ui-select for display purpose,
value-prop - the name of the property which will be used for model assignment,
multiple [optional] - if multiple selection is allowed

在指令子范围内,我有与ui-select ng-model同步的对象,当它被更改时,我正在更新主范围。

当您选择空白时,我设法让所选项目和多个项目都有效。但是,当选择多个选择时,我仍然有问题显示初始选定项目。我认为问题出在我的指令和ui-select指令之间的范围和$ watch方法的某处。看起来我的指令范围内的更新不会影响数组中的ui-select ng-model。
我使用包含指令和测试用例的简单应用程序创建了一个Plunker,您可以看到单个选择正常工作,但是当我有一个数组时,列表未初始化。

angular.module('dgUi', ['ui.select', 'ngSanitize'])

  .config(['uiSelectConfig', function(uiSelectConfig){
    uiSelectConfig.theme = 'select2';
  }])

  .controller('UiSelectWrapperConttoller', ['$scope', function($scope){
    $scope.userAddresses = [
      {
        address: 'Address 1',
        description: 'Home address'
      },
      {
        address: 'Address 2',
        description: 'Office address'
      },
      {
        address: 'Address 3',
        description: 'Test address 3'
      },
      {
        address: 'Address 4',
        description: 'Test address 4'
      }
    ];

    $scope.currentUser = {
      name: 'User 1',
      address: 'Address 1'
    };

    $scope.currentUser = {
      name: 'User 1',
      address: 'Address 2',
      availableAddresses:['Address 3']
    };
  }])

  .directive('dgSelect', ['$parse', function ($parse) {
        return {
            restrict: 'AE',
            require: ['ngModel'],
            scope: true,
            templateUrl: function(tElement, tAttrs) {
                return '/global/dg-ui/dg-select' + ((angular.isDefined(tAttrs.multiple) ? '-multi' : '') + '.tpl.html');
             },
            compile: function (tElement, tAttrs) {
              var displayPropSufix = tAttrs.displayProp ? '.' + tAttrs.displayProp : '';
                var isMultiple = angular.isDefined(tAttrs.multiple) ;

                //match element config
                if (tAttrs.placeholder) {
                    $('ui-select-match, *[ui-select-match]', tElement).attr('placeholder', tAttrs.placeholder);
                }

                if(isMultiple){
                    $('ui-select-match, *[ui-select-match]', tElement).html('{{$item' + displayPropSufix + '}}');
                }else{
                    $('ui-select-match, *[ui-select-match]', tElement).html('{{$select.selected' + displayPropSufix + '}}');
                }


                //choices element config
                $('ui-select-choices, *[ui-select-choices]', tElement).attr('repeat', 'listItem in ' + tAttrs.items + ' | filter:$select.search')
                $('ui-select-choices, *[ui-select-choices]', tElement).html('<div ng-bind-html="listItem' + displayPropSufix + ' | highlight: $select.search"></div>');
                return function link(scope, element, attrs, ctrls) {
                    scope.ngModel = ctrls[0];
                    scope.isMultiple = angular.isDefined(attrs.multiple) 
                    scope.itemsGetter = $parse(attrs.items);
                    if(angular.isDefined(attrs.valueProp) && attrs.valueProp !== ''){
                        scope.valuePropGetter = $parse(attrs.valueProp);
                    }

                    scope.getValueMapper = function(itemObject){
                        return scope.valuePropGetter ? scope.valuePropGetter(itemObject) : itemObject;
                    }


                    scope.updateValueFromModel = function(modelValue){
                        if(scope.isMultiple){
                            var selectionArray = [];
                            angular.forEach(modelValue, function(modelItem, key){
                                var modelItemValue = scope.getValueMapper(modelItem);
                                selectionArray.push(modelItemValue);
                            });
                            scope.selectionModel = selectionArray;
                        }else{
                            var items = scope.itemsGetter(scope);
                            angular.forEach(items, function(item, key){
                                var itemValue = scope.getValueMapper(item);
                                if(itemValue == modelValue){
                                    scope.selectionModel = item;
                                    return false;
                                }
                            });
                        }
                    }

                    if(scope.isMultiple){
                        scope.$watchCollection(attrs.ngModel, function(modelValue, oldValue) {
                            scope.updateValueFromModel(modelValue);
                        }); 
                    }else{
                        scope.$watch(attrs.ngModel, function(modelValue){
                            scope.updateValueFromModel(modelValue);
                        });
                    }

                    //watch the items in case of async loading
                    //scope.$watch(attrs.items, function(){
                    //  scope.updateValueFromModel(scope.ngModel.$modelValue);
                    //});

                    scope.onItemSelect = function(item, model){
                        var movelValue = scope.getValueMapper(item);
                        if(scope.isMultiple){
                            scope.ngModel.$viewValue.push(movelValue);
                        }else{
                            scope.ngModel.$setViewValue(movelValue);
                        }
                    }

                    scope.onItemRemove = function(item, model){
                        var removedModelValue = scope.getValueMapper(item);
                        if(scope.isMultiple){
                          var removeIndex = null;
                          angular.forEach(scope.ngModel.$viewValue, function(itemValue, index){
                              if(itemValue == removedModelValue){
                                    removeIndex = index;
                                    return false;
                                }
                            });
                            if(removeIndex){
                              scope.ngModel.$viewValue.splice(removeIndex, 1);
                            }
                        }else{
                            scope.ngModel.$setViewValue(movelValue);
                        }
                    }

                }
            }
        };
    }])

.run(['$templateCache', function ($templateCache) {
        $templateCache.put('/global/dg-ui/dg-select.tpl.html',
          '<ui-select class="ui-select" ng-model="selectionModel" on-select="onItemSelect($item, $model)" on-remove="onItemRemove($item, $model)" ng-disabled="disabled"><ui-select-match></ui-select-match><ui-select-choices></div></ui-select-choices></ui-select>');
        $templateCache.put('/global/dg-ui/dg-select-multi.tpl.html',        '<ui-select class="ui-select" multiple ng-model="selectionModel" on-select="onItemSelect($item, $model)" on-remove="onItemRemove($item, $model)" ng-disabled="disabled"><ui-select-match></ui-select-match><ui-select-choices></ui-select-choices></ui-select>');
    }]);

可能我在这里做错了什么。我非常感谢任何帮助:),谢谢!

1 个答案:

答案 0 :(得分:0)

ui-select中已经有这样的功能。所以只需在转发器中指定属性,如下所示:

repeat="item.indexProp as item in myCtrl.items"

整个标记看起来像这样:

<ui-select ng-model="myCtrl.selectedItem" theme="select2">
  <ui-select-match placeholder="Select an item...">{{$select.selected.captionProp}}</ui-select-match>
  <ui-select-choices repeat="item.indexProp as item in myCtrl.items | filter: $select.search" value=" {{$select.selected.indexProp}}">
    <div ng-bind-html="item.captionProp | highlight: $select.search"></div>
  </ui-select-choices>
</ui-select>

因此,如果您的项目如下:

{indexProp:1,captionProp:&#39;项目名称&#39;}

ui-select将显示项目&#34; captionProp&#34;在下拉列表中传递&#34; indexProp&#34;进入你的ng模型。