是否可以在焦点上扩展ngOptions下拉菜单?

时间:2014-09-18 12:46:19

标签: angularjs angularjs-directive

如果我点击a,则会扩展ngOptions列表。键盘导航期间是否可以在onFocus上获得相同的行为?

1 个答案:

答案 0 :(得分:1)

您可以创建一个指令,将焦点事件附加到选择标记,并在焦点和模糊期间操纵选择标记的size property。下面是一个代码段,其中包含一个指令expandFocus,它演示了焦点上的选项选项的扩展及其对模糊的收缩。

angular.module('demo', [])

  .controller('Ctrl', function($scope) {
     $scope.colors = [
        {name:'black', shade:'dark'},
        {name:'white', shade:'light'},
        {name:'red', shade:'dark'},
        {name:'blue', shade:'dark'},
        {name:'yellow', shade:'light'}
     ];
  })

  .directive('expandFocus', function() {
     return function(scope, jqElem, attr) {
         var elem = jqElem[0],
             tag = elem.tagName.toLowerCase();

         if(tag == 'select') {
         	jqElem.on('focus', function() {
               elem.size = elem.length;
            });

            jqElem.on('blur', function() {
               elem.size = 0; // normally you would use 1 but firefox uses 0.
            });

            scope.$on('$destroy', function() {
              elem.off('focus');
              elem.off('blur');
            });
         }
     };
  });
<div ng-app="demo" ng-controller="Ctrl">
	<select ng-options="color.name for color in colors" ng-model="mainColor" name="mainColor" expand-focus>
      <option value=""> -- Select </option>
  	</select>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>