Ng-click在自动填充中的选定列表项中不起作用?

时间:2017-04-17 08:36:42

标签: javascript angularjs

我无法使用ng-click选择列表项。当我点击所选项目时,我必须获取所选项目的ID,并且所选项目必须显示在搜索框中。但它对于输入键工作正常,但我也希望在搜索框中选择的项目为ng-点击。

这是我的代码。

JS:

angular.module("hmautocomplete", [])
.directive('hmAutocomplete', function ($timeout) {
  return {
      scope: {
          selectedIndex: '=',
          hmSuggestions: '=',
          hmDropdownid: '@',
          hmSelect: '&'
      },

      link: function (scope, element) {

          scope.selectedIndex = 0;

          var elem = angular.element(document.getElementById('autotext'));
          var list = 
        angular.element(document.getElementById(scope.hmDropdownid));

          list.css('display', 'none');

          elem.bind('focus', function () {
              scope.selectedIndex = 0;
              scope.$apply();
              list.css('display', 'block');
          });

          elem.bind('blur', function () {
              $timeout(
                function () {
                    list.css('display', 'none');
                }, 100
              )
          });

          elem.bind("keydown", function (event) {


              if (list.css('display') === 'none') {
                  list.css('display', 'block');
              }

              if (event.keyCode === 40) { //down key, increment 
         selectedIndex
                  event.preventDefault();
                  if (scope.selectedIndex + 1 === 
        scope.hmSuggestions.length) {
                      scope.selectedIndex = 0;
                  } else {
                      scope.selectedIndex++;
                  }
                  scope.$apply();
              } else if (event.keyCode === 38) { //up key, decrement 
         selectedIndex
                  event.preventDefault();

                  if (scope.selectedIndex === 0) {
                      scope.selectedIndex = scope.hmSuggestions.length - 1;
                  } else {
                      scope.selectedIndex--;
                  }
                  scope.$apply();

              } else if (event.keyCode === 13 || event.keyCode === 9) { 
       //enter pressed or tab

                  elem.val(scope.hmSuggestions[scope.selectedIndex].Name);
                  list.css('display', 'none');
                  scope.hmSelect(scope.hmSuggestions[scope.selectedIndex]);
                  scope.$apply();

              } else if (event.keyCode === 27) {
                  list.css('display', 'none');
              }
          })

      }
  };
    }).directive('hoverClass', function () {
  return {
      restrict: 'A',
      link: function (scope, element, attr) {

          element.on('mouseenter', function () {

   angular.element(document.getElementsByClassName(attr.hoverClass)).removeClass(attr.hoverClass);
              element.addClass(attr.hoverClass);
          });

          element.on('mouseleave', function () {
              element.removeClass(attr.hoverClass);
          });

      }
  };
  })

.directive('hmSelectDown', function () {
return {
    restrict: 'A',
    scope: {
        hmSelectDown: '&'
    },
    link: function (scope, elem, attr) {
        var list = angular.element(document.getElementById(scope.hmDropdownid));
        elem.bind('click', function () {
            scope.hmSelectDown();
            list.css('display', 'none');
        });
    }
};
  })

  .filter('highlight', function ($sce) {
   return function (text, phrase) {
    if (phrase)
        text = text.replace(new RegExp('(' + phrase + ')', 'gi'), '<span 
class="highlighted">$1</span>');
    return $sce.trustAsHtml(text);
}
  }).controller('demo', function ($scope) {


$scope.fnAutocompleteQuestion = function () {
    $scope.items = [{
        'Name': 'India'
    }, { 'Name': 'United States' },
        { 'Name': 'England' },
        { 'Name': 'Germany' },
        { 'Name': 'London' }, {
            'Name': 'Pakistan'
        }, {
            'Name': 'Nepal'
        }, {
            'Name': 'Bangladesh'
        }];
}
$scope.onselect = function (obj) {
    alert(JSON.stringify(obj));
    console.log(obj);
}

 });

HTML:

  <div ng-controller="demo">
    <hm-autocomplete selected-index="selectedIndex"
                     hm-textboxid="autotext"
                     hm-dropdownid="dropdown"
                     hm-suggestions="items"
                     hm-select="onselect(items[selectedIndex])">
        <input type="text" id="autotext" class="form-control" ng-model="strSearch"  ng-change="fnAutocompleteQuestion(strSearch)" />
        <ul id="dropdown" class="ngcomplete-dropdown">
            <li ng-repeat="item in items | filter: strSearch" 
                hover-class='ngcompleterowactive'
                ng-mouseover='selectedIndex==$index'
                ng-class="{'ngcompleterowactive':selectedIndex==$index}"
                ng-bind-html="item.Name | highlight:strSearch"
                hm-select-down="onselect(item)">
            </li>
        </ul>
    </hm-autocomplete>
</div>

2 个答案:

答案 0 :(得分:2)

我想你可以试试这个

JS

 }).controller('demo', function($scope) {

     //  code..

     $scope.selectedItem;

     $scope.selectItem = function(item){
        $scope.selectedItem = item;
         $scope.strSearch = $scope.selectedItem.Name;
     }

     // code..
})

HTML

    <li ng-repeat="item in items | limitTo:10"
                class="ngcompleterow"
                hover-class='ngcompleterowactive'
                ng-click="selectItem(item)"
                ng-mouseover='selectedIndex==$index'
                ng-class="{'ngcompleterowactive':selectedIndex==$index}"
                        ng-bind-html="item.Name | highlight:strSearch"
                hm-select-down="onselect(item)"
            >
    </li>

<强>更新

我发现为什么没有通过第一次点击选择它,原因是因为你有这种结构:

      elem.bind('focus', function () {
          scope.selectedIndex = 0;
          scope.$apply();
          list.css('display', 'block');
      });

      elem.bind('blur', function () {
          $timeout(
            function () {
                list.css('display', 'none');
            }, 100
          )
      });

所以,如果你删除它,并重构:

JS:

  .controller('demo', function($scope) {

  // code

  $scope.blurDropdown = function(){
     // same thing as $timeout
     setTimeout(function(){
        $scope.showDropdown = false;
        $scope.$apply();
     }, 100)

    // code

  });

}

和HTML

   <input ng-focus="showDropdown = true" ng-blur="blurDropdown()" type="text" id="autotext" class="form-control" ng-model="strSearch" />

   <ul id="dropdown" data-ng-show="showDropdown" class="ngcomplete-dropdown">

在修复之后,我可以点击与搜索模式匹配的任何元素。

Plunker示例

答案 1 :(得分:0)

如果您希望所选项目显示在搜索或文本框中,请按以下方式更新您的方法,

 $scope.onselect = function(obj) {
      alert(JSON.stringify(obj));
      $scope.strSearch = obj.Name;
      console.log(obj);
 }