【问题标题】:ionic directive remove first option from select离子指令从选择中删除第一个选项
【发布时间】:2015-12-24 03:13:28
【问题描述】:

我正在尝试制定一个指令,该指令应该删除选择的第一个选项。

我正在使用这个 html 来生成选择框:

 <select remove-whitespace ng-model="user.encryption">                                      
      <option ng-repeat="r in selectButtons" title="{{r.text}}" ng-selected="$first" value="{{r.value}}">{{r.text}}</option>                            
 </select>

这部分代码在我的控制器中用于填充视图中的选择框:

    $scope.selectButtons = [
        {text: "Clear-Text", value: "no_encryption"},
        {text: "MD5", value: "md5_encryption"},
        {text: "SHA1", value: "sha1_encryption"},
    ];

我用这个作为我的指令:

.directive("removeWhitespace", function () {
    return{
        require: 'ngModel',
        link: function (scope, element, attributes, ngModel) {            
            console.log(element.context); 
        }
    }
});

当我做一个 console.log(element.context);以下上下文出现在我的浏览器控制台中:

但是我似乎无法删除值为“?未定义:未定义?”的选项

【问题讨论】:

    标签: javascript angularjs select ionic directive


    【解决方案1】:

    第一个元素 (? udefined:undefined ?) 存在是因为 ng-model 的当前值与任何选项都不匹配。如果您在控制器中执行以下操作,它会自行消失:

    $scope.user.encryption="no_encryption"
    

    为了完全回答这个问题,这里有一个简单的指令,它删除了 select 的第一个选项,但我建议不要使用类似的东西,因为最好使用 ng-options 可能与过滤器结合使用

    angular.module('app').directive('removeFirst',function(){
      return{
        link:function(scope,element) {
          element.find('option')[0].remove();
        },
      }
    })
    

    【讨论】:

      【解决方案2】:

      看来我已经找到了解决我自己问题的方法:

      要正确填充选择框,您需要使用 ng-options 而不是 ng-repeat。

      我最终使用了以下内容:

           <select ng-model="selectButton"
            ng-options="r.text for r in selectButtons">                                
           </select>
      

      这将填充一个没有空格的选择框。并且不再需要该指令。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-08
        • 2021-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-30
        相关资源
        最近更新 更多