ng-repeat,在指令内使用ng-click

亚历克斯·海恩斯(Alex Haines)

我正在尝试创建一个简单的自动完成标记指令。但是ng-click下拉菜单上的<li>不会触发。我确定这是某种范围的问题,但我不知道为什么。有人可以告诉我如何使此ng-click触发吗?谢谢!

这是模板:

<article ng-click="focus()">

  <div class="tags-container">

    <div ng-repeat="selectedTag in selectedTags" ng-click='removeTag($index)' class="tag">
      <span class="tagName">{{selectedTag}}</span>
    </div>

    <input type="text" ng-focus='activate()' ng-blur='listActive = false' id="searchInput" ng-keydown="checkKeyDown($event)" class="tags" ng-model="searchText" />

  </div>

  <ul id="suggestions" class="suggestions-list" ng-class="{active : listActive}">
    <li ng-repeat="tag in tagList | filter:searchText" class="tags" ng-click="addToSelectedTags($index)" ng-mouseover="$parent.index=$index" ng-class="{active : index===$index}">
      <strong>{{tag}}</strong>
    </li>
  </ul>

</article>

这是指令

angular
  .module('directives')

.directive('tagComplete', function() {
  return {
    restrict: 'AE',
    scope: {
      selectedTags: '=',
      tagList: '='
    },
    templateUrl: 'public/partials/tagAutocomplete.html',
    link: function(scope, elem, attrs) {
      scope.index = -1;
      scope.listActive = false;
      scope.test = 'false';

      scope.removeTag = function(index) {
        scope.selectedTags.splice(index, 1);
      };

      scope.addToSelectedTags = function(index) {
        var isSelected = _.includes(scope.selectedTags, scope.tagList[index]);

        if (!isSelected) {
          scope.selectedTags.push(scope.tagList[index]);
          scope.searchText = '';
          scope.index = -1;
        }
      };

      scope.focus = function() {
        console.log(scope.test);
        $(elem).find('#searchInput').focus();
      };

      scope.activate = function() {
        if (scope.tagList.length > 0) {
          scope.listActive = true;
        }
      };

      scope.checkKeyDown = function(event) {
        if (event.keyCode === 40) {
          event.preventDefault();
          if (scope.index + 1 !== scope.tagList.length) {
            scope.index++;
          }
        } else if (event.keyCode === 38) {
          event.preventDefault();
          if (scope.index - 1 !== -1) {
            scope.index--;
          }
        } else if (event.keyCode === 13) {
          scope.addToSelectedTags(scope.index);
        } else {
          scope.index = -1;
        }
      };
    }
  }
});

这是html中的指令

<tag-complete tag-list="vm.suggestions" selected-tags='vm.query.fields'></tag-complete>
凯尔·伊瓦尔(Kjell Ivar)

您的ng-click应该触发了。我尝试将您的代码输入到小提琴中,并对其进行了一些修改:http : //jsfiddle.net/vt52bauu/5/

您可以尝试单击锂元素。我发现这部分代码有问题:

ng-click="addToSelectedTags($index)"

当您将某些内容写入searchInput时,它将过滤您的ng-repeat列表。因此,$ index将与您的tagList中的索引不匹配,并且它可能会尝试添加您的selectedTags列表中已经存在的内容。我将其更改为直接输入标签:

ng-click="addToSelectedTags(tag)"

我在代码中所做的其他更改只是为了使其在jsFiddle内部运行。这对您有帮助吗?我能想到的唯一的另一件事是与css有关的东西。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章