【问题标题】:Conditional multi-select directive in angular角度中的条件多选指令
【发布时间】:2015-12-10 22:57:13
【问题描述】:

我正在创建一个选择框指令,作为其中的一部分,我需要指定选择是否为多个。

我试图在我的一个范围对象中设置一个多重属性的值“多个”,假设它应该执行并在我的选择框上设置multiple="multiple",如下所示:

<select multiple="{{properties.multiple}}" /*...(other working properties)...*/ ></select>

但这让我出错了..

Error: [$compile:selmulti] http://errors.angularjs.org/1.4.4/$compile/selmulti?p0=%3Cselect%20id%3D%22…y%20as%20value%20for%20(key%20%2C%20value)%20in%20properties.options%22%3E
    at Error (native)
    at path/to/angular/angular-1.4.4/angular.min.js:6:416
    at X (path/to/angular/angular-1.4.4/angular.min.js:71:93)
    at ha (path/to/angular/angular-1.4.4/angular.min.js:56:379)
    at S (path/to/angular/angular-1.4.4/angular.min.js:54:425)
    at path/to/angular/angular-1.4.4/angular.min.js:68:209
    at path/to/angular/angular-1.4.4/angular.min.js:118:217
    at n.a.$get.n.$eval (path/to/angular/angular-1.4.4/angular.min.js:133:39)
    at n.a.$get.n.$digest (path/to/angular/angular-1.4.4/angular.min.js:130:60)
    at n.scopePrototype.$digest (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:1955:23)

我可以使用ng-if,但我试图找到一种比制作冗余选择标签更好的方法来区分标准和多个。

还有什么更好的方法?

【问题讨论】:

    标签: javascript angularjs multi-select


    【解决方案1】:

    创建您自己的使用ng-ifs 的指令,或者编写一个带有逻辑的指令以在单个和多个之间切换。看起来 Angular 不想这样做,但如果它适合你,那就去吧。

    【讨论】:

      【解决方案2】:

      一种可能性是在你的指令定义中添加一个链接函数,检查你的范围之外的 properties.multiple 值,然后使用 jquery 或 jqLit​​e 来设置属性。所以:

      angular.directive("yourDirective", function() {    return {
            link: function(scope, element, attrs) {
                 if (scope.properties.multiple) {
                    elements.children("select").attr("multiple",true);
                 }
            },
            templateUrl: "yourtemplate.html", ...    
            } 
      });
      

      【讨论】:

      • 由于这使选择框成为多选,但它的行为并不正常。这意味着如果您将 ng-model 值设置为选择框的["2"],则不会选择带有value="2" 的选项(知道它存在)。此外,这在value="?" 的多选中创建了一个空选项。我也尝试使用控制器而不是链接,但没有运气.. 我想我会选择ng-if。谢谢你的帮助..
      猜你喜欢
      • 2017-10-31
      • 1970-01-01
      • 2020-03-24
      • 2017-04-01
      • 1970-01-01
      • 2016-05-05
      • 1970-01-01
      • 2015-01-30
      • 2015-08-26
      相关资源
      最近更新 更多