AngularJS 与语义-UI

AngularJS with Semantic-UI's

我正在使用 Semantic-UI 的多选下拉菜单,我在 AngularJS 中有以下指令来设置下拉菜单的值:

.directive('suiSelectionDropdown', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attrs, modelCtrl) {
      if(!modelCtrl) return;

      // the timeout ensures that Semantic-UI's dropdown is set only after
      // AngularJS had a chance to unroll the repeater that creates the options.
      $timeout(function() {
        element.dropdown('set selected', modelCtrl.$viewValue);
      }, 0);

      var allow;
      if(attrs.suiSelectionDropdown === 'allowAdditions') allow = true;
      else allow = false;

      element.dropdown({
        allowAdditions: allow,
        maxSelections: attrs.maxSelections || undefined,
        inline: true,
        onChange: function (value, text, $choice) {
          modelCtrl.$setViewValue(value);
        }
      });
    }
  };

指令的使用如下:

<div class="ui multiple search selection dropdown" ng-model="(info).slide.tags"
                                                   sui-selection-dropdown="allowAdditions"
                                                   max-selections="5">
  <input name="tags" type="hidden" value="">
  <i class="dropdown icon"></i>
  <div class="default text"></div>
  <div class="menu">
    <div class="item" ng-repeat="tag in tagList track by (tag._id)" data-value="{{tag._id}}">{{tag.name}}</div>
  </div>
</div>

标签列表是通过 AJAX 请求获得的,模型也可能在开始时包含一些值。

用户可以使用已有的标签或输入新的标签。如果添加了新标签,我需要更新服务器上的标签列表,return,并再次相应地设置模型。但是我在如何执行此操作方面遇到了一些问题:标签列表正在正确更新,但模型不是!

// Controller
Edition.updateInformation(obj, modified)
  .then(function(response) {
      prevInfo = angular.copy(obj);
      Tag.getAllTags()
         .then(function(response) {
           $scope.tagList = Tag.retrieveTagList();
         }); 
  });

// Service
tag.retrieveTagList = function() {
  return tagList;
};

tag.getAllTags = function() {
  var defer = $q.defer();

  $http({
    method: 'GET',
    url: '/api/extra/tags',
    skipAuthorization: true // the Bearer token will not be sent
  }).success(function(response) {
    angular.copy(response.tags, tagList);
    defer.resolve(response);
  }).error(function(response) {
    defer.reject(response);
  });

  return defer.promise;
};

新添加的标签出现在下拉列表菜单中,但好像它们没有被选中(添加到模型中)。

你能帮帮我吗?

我设法让它工作了。它仍然不完美,但它很实用......!

在我的指令中,我包含了以下代码来观察标签列表中的任何变化,然后相应地更新模型:

// watch for any changes in the list of tags
// every time a new tag is added we need to update the list of tags and the model accordingly
scope.$watch('tagList', function(newValue, oldValue) {
  if(newValue && newValue !== oldValue) {
    var temp = modelCtrl.$viewValue;
    element.dropdown('clear');
    $timeout(function() {
      element.dropdown('set selected', temp);
    }, 0);
  }
}, true);