значение в ng-модели с ‹ui-select› не такое, как с родным ‹select›

Я хотел заменить родной <select> фреймворком angular-ui-select <ui-select>. Но у меня проблема, поскольку значение переменной ng-model не остается прежним после замены. Думаю, я как-то не совсем понял ui-select.

Ниже моего кода до и после замены:

С тегом nativ <select>

<select class="form-control ll-selbox ll-ptrhand" ng-model="newitem.type" ng-options="item.id as item.title | translate for item in types" ng-selected="updateComboboxes(0)"></select>

в $scope.types: (copy()ed вне консоли)

[
  {
    "id": "CT",
    "title": "WFLOWEDIT.OPT1.CT"
  },
  {
    "id": "MD",
    "title": "WFLOWEDIT.OPT1.MD"
  },
  {
    "id": "DT",
    "title": "WFLOWEDIT.OPT1.DT"
  },
  {
    "id": "CO",
    "title": "WFLOWEDIT.OPT1.CO"
  },
  {
    "id": "P",
    "title": "WFLOWEDIT.OPT1.P"
  }
]

in $scope.newitem.type:

"CT" (строка)

С тегом angular-ui-select-Framework-Tag:

<ui-select class="ll-selbox " ng-model="newitem.type" theme="bootstrap" on-select="updateComboboxes(0)">
    <ui-select-match>{{$select.selected.title | translate}}</ui-select-match>
    <ui-select-choices location="wflowmodify" repeat="item in types | filter: $select.search" refresh-delay="0">
        <span ng-bind-html="item.title | translate | highlight: $select.search"></span>
    </ui-select-choices>
</ui-select>

в $scope.types: (copy()ed вне консоли)

[
  {
    "id": "CT",
    "title": "WFLOWEDIT.OPT1.CT",
    "$$hashKey": "object:114"
  },
  {
    "id": "MD",
    "title": "WFLOWEDIT.OPT1.MD",
    "$$hashKey": "object:115"
  },
  {
    "id": "DT",
    "title": "WFLOWEDIT.OPT1.DT",
    "$$hashKey": "object:116"
  },
  {
    "id": "CO",
    "title": "WFLOWEDIT.OPT1.CO",
    "$$hashKey": "object:117"
  },
  {
    "id": "P",
    "title": "WFLOWEDIT.OPT1.P",
    "$$hashKey": "object:118"
  }
]

в $scope.newitem.type: (copy()ed вне консоли)

{
  "id": "CT",
  "title": "WFLOWEDIT.OPT1.CT",
  "$$hashKey": "object:114"
}

controller:

cmod.controller('WorkflowModifierEditorCtrl', function ($rootScope, $scope, $modalInstance, i18n, subtitle, procid, modifiers, Restangular, WorkflowModifyService, AlertService, featureFlags) {
  $scope.modifiers = modifiers;
  $scope.subtitle = subtitle;
  $scope.procid = procid;

  $scope.types = [];
  $scope.codes = [];
  $scope.triggers = [];
  $scope.resolutions = [];

  $scope.newitem = {type: 'CT', code: '', trigger: '', res: ''};

  $scope.refreshData = function () {
    // Calling route CHECK_8
    Restangular.one('wflowmod').get({proc: procid}).then(function (data) {
      // types of rules ("workflow modifiers")
      if (data.checktypes && data.checktypes.length > 0) $scope.types.push({id: 'CT', title: 'WFLOWEDIT.OPT1.CT'});
      if (data.models && data.models.length > 0) $scope.types.push({id: 'MD', title: 'WFLOWEDIT.OPT1.MD'});
      if (data.devicetypes && data.devicetypes.length > 0) $scope.types.push({id: 'DT', title: 'WFLOWEDIT.OPT1.DT'});
      if (featureFlags.isOn("configtable") && data.configtables && data.configtables.length > 0) $scope.types.push({
        id: 'CO',
        title: 'WFLOWEDIT.OPT1.CO'
      });

      if (data.procedures && data.procedures.length > 0) $scope.types.push({id: 'P', title: 'WFLOWEDIT.OPT1.P'});
      if (data.steps && data.steps.length > 0) $scope.types.push({id: 'S', title: 'WFLOWEDIT.OPT1.S'});
      if (data.measures && data.measures.length > 0) $scope.types.push({id: 'M', title: 'WFLOWEDIT.OPT1.M'});
      if ($scope.types.length < 1) $modalInstance.dismiss();
      $scope.newitem.type = $scope.types[0].id;
      $scope.resdata = data;
      $scope.updateComboboxes(0);
      $scope.wfmods = WorkflowModifyService.getWorkflowModifiersForDisplay($scope.modifiers);
      $scope.wfModEditorLoaded = true;
    }, AlertService.showSevereRESTError)
  };

  $scope.oldType = null;
  $scope.oldTrigger = null;

  $scope.updateComboboxes = function (what) {
    console.log($scope.types);
    console.log($scope.newitem.type);
    // $scope.newitem.type = $scope.newitem.type.id;
    if (!$scope.resdata) return;
    if (what == 0) {
      if ($scope.oldType == $scope.newitem.type) return;
      $scope.oldType = $scope.newitem.type;
      $scope.codes = _.map(
        $scope.resdata[{
          CT: 'checktypes',
          MD: 'models',
          DT: 'devicetypes',
          P: 'procedures',
          S: 'steps',
          M: 'measures',
          CO: 'configtables'
        }[$scope.newitem.type]],
        function (entry) {
          var lang = i18n.getSelectedLanguage()['code'];
          var listitem = {};
          if (typeof entry === "string") {
            listitem.id = entry;
            listitem.title = entry;
          }
          else {
            // title will be translated when available, else just set the whole (e.g. configtables)
            listitem.id = entry[0];
            listitem.title = entry[0] + " - " + ( entry[1][lang] ? i18n.translate(entry[1]) : entry[1] );
          }
          return listitem;
        }
      );
      $scope.newitem.code = $scope.codes[0].id;
      var triggers = [];
      if (_.contains(['CT', 'MD', 'DT'], $scope.newitem.type)) {
        triggers.push({id: 'Select', title: 'WFLOWEDIT.OPT2.SEL'});
        triggers.push({id: '!Select', title: 'WFLOWEDIT.OPT2.NSEL'});
      }
      if (_.contains(['CO'], $scope.newitem.type)) {
        triggers.push({id: '!Select', title: 'WFLOWEDIT.OPT2.NACTIVE'});
        triggers.push({id: 'Select', title: 'WFLOWEDIT.OPT2.ACTIVE'});
      }
      if (_.contains(['P'], $scope.newitem.type)) {
        triggers.push({id: 'InQueue', title: 'WFLOWEDIT.OPT2.QUEUED'});
        triggers.push({id: '!InQueue', title: 'WFLOWEDIT.OPT2.NQUEUED'});
      }
      if (_.contains(['P', 'M', 'S'], $scope.newitem.type)) {
        triggers.push({id: 'Pass', title: 'WFLOWEDIT.OPT2.FINPASS'});
        triggers.push({id: 'Fail', title: 'WFLOWEDIT.OPT2.FINFAIL'});
        triggers.push({id: 'Skip', title: 'WFLOWEDIT.OPT2.SKIP'});
        triggers.push({id: '!Skip', title: 'WFLOWEDIT.OPT2.NSKIP'});
        triggers.push({id: 'Omit', title: 'WFLOWEDIT.OPT2.OMIT'});
        triggers.push({id: '!Omit', title: 'WFLOWEDIT.OPT2.NOMIT'});
      }
      if (_.contains(['M'], $scope.newitem.type)) {
        triggers.push({id: 'Yes', title: 'WFLOWEDIT.OPT2.YES'});
        triggers.push({id: 'No', title: 'WFLOWEDIT.OPT2.NO'});
      }
      $scope.triggers = triggers;
      $scope.newitem.trigger = $scope.triggers[0].id;
    }
    if ($scope.oldTrigger == $scope.newitem.trigger) return;
    $scope.oldTrigger = $scope.newitem.trigger;
    var resolutions = [{id: 'omit', title: 'WFLOWEDIT.OPT3.OMIT'}];
    if (!_.contains(['Select', '!Select', 'InQueue', '!InQueue'], $scope.newitem.trigger)) resolutions.push({
      id: 'skip',
      title: 'WFLOWEDIT.OPT3.SKIP'
    });
    $scope.resolutions = resolutions;
    $scope.newitem.res = $scope.resolutions[0].id;
  };

  $scope.addWorkflowModifier = function () {
    var newitem = {};
    newitem.type = $scope.newitem.type;
    newitem.code = $scope.newitem.code;
    newitem.res = $scope.newitem.res;
    if ($scope.newitem.trigger.substr(0, 1) == "!") {
      newitem.trigger = $scope.newitem.trigger.substr(1);
      newitem.inverse = true;
    } else {
      newitem.trigger = $scope.newitem.trigger;
    }
    $scope.modifiers.push(newitem);
    $scope.wfmods = WorkflowModifyService.getWorkflowModifiersForDisplay($scope.modifiers);
  };

  $scope.removeWorkflowModifier = function (idx) {
    var el = $scope.modifiers[idx - 1];
    if (el.type === 'CO') {
      var type = $scope.subtitle.msg.charAt(0).toLowerCase();
      var id = $rootScope.selecteditem.id;
      Restangular.one('configentry', el.code).one('blocker', type).one('id', id).remove().then(function (data) {
        // pass
      }, AlertService.showSevereRESTError);
    }

    $scope.modifiers.splice(idx - 1, 1);
    $scope.wfmods = WorkflowModifyService.getWorkflowModifiersForDisplay($scope.modifiers);
  };

  $scope.refreshData();

  $scope.close = function () {
    $modalInstance.close()
  };
});

person RagnarLodbrok    schedule 29.03.2017    source источник
comment
Итак, проблема в том, что вам не нужен хэш-ключ $$ в ваших данных?   -  person Cameron Rodriguez    schedule 29.03.2017


Ответы (1)


Это исходит от вашего ui-select:

<ui-select-choices location="wflowmodify" repeat="item in types | filter: $select.search" refresh-delay="0">

но чтобы составить структуру select, вы должны сделать:

<ui-select-choices location="wflowmodify" repeat="item.id as item in types | filter: $select.search" refresh-delay="0">

Обратите внимание, что item.id отличается. Вы должны сопоставить фильтр с полем вашего элемента (я не знаю, по какому из них вы хотите отфильтровать)

person Groben    schedule 29.03.2017
comment
Спасибо. Я хотел бы отфильтровать item.title, который выводится в <span ng-bind-html="item.title | translate | highlight: $select.search"></span>. Правильно ли я предполагаю, что сейчас фильтрую item.id? - person RagnarLodbrok; 29.03.2017
comment
Я не уверен. Но вот ссылка, которая может помочь вам с фильтрами stackoverflow.com/questions/42972381/ - person Groben; 30.03.2017
comment
Теперь я знаю, почему этого не произошло, почему фильтр сначала не сработал. Я использовал переводы i18n. Мне сначала пришлось перевести значения в контроллер (вместо этого я сделал это в представлении) - person RagnarLodbrok; 30.03.2017
comment
Да, но с предоставленной мной ссылкой он показывает пример сохранения результата фильтра в переменной прямо из представления. Таким образом, вы можете сохранить результат перевода в переменной, а затем применить свой фильтр. Хотя и сам не знаю, как это делать. - person Groben; 30.03.2017
comment
Или может быть что-то вроде этого: filter: $ select.search: (item.title | translate) - person Groben; 30.03.2017