ng-select 选项在与自定义指令一起使用时加倍

ng-select options are doubled when used with a custom directive

本文关键字:一起 指令 选项 自定义 ng-select      更新时间:2023-09-26

我正在尝试实现动态可配置的字段。我将从服务器获取验证规则 ng-required、ng-hidden、ng-disabled 等属性作为 json,并通过指令动态设置它们。

我有以下指令代码。它显示选择值加倍 JsBin 链接 http://jsbin.com/jiququtibo/1/edit

var app = angular.module('myapp', []);
app.directive('inputConfig', function( $compile) {
  return {
        require: 'ngModel',
        restrict: 'A',
        scope: '=',
        compile: function(tElem, tAttrs){
            console.log("compile 2");
            tElem.removeAttr('data-input-config');
            tElem.removeAttr('input-config');
            tElem.attr('ng-required',true);
            return {
                pre: function (scope, iElement, iAttrs){
                    console.log('pre');
                },
                post: function(scope, iElement, iAttrs){
                    console.log("post");
                    $compile(tElem)(scope);
                }
            }
        }
    };
});

如何解决此问题?我应该能够动态添加指令。

要解决您的问题,您需要从 post 函数中删除以下行:

$compile(tElem)(scope);

我不清楚你为什么要在这里编译,所以我不确定这是否会有任何意想不到的副作用。

我发现以下代码的解决方案正在工作。你应该首先克隆,删除指令,准备dom并编译

   app.directive('inputConfig', function( $compile) {        返回 {            要求:"?ng模型",            限制:"A",            编译:function (t, tAttrs, transclude){                var tElement = t.clone() ;                tElement.removeAttr('input-config');                tElement.attr('ng-required',true);                t.attr('ng-required',true);                返回函数(范围){                    首先准备 DOM                    t.replaceWith(tElement);                    比编译                    $compile(tElement)(scope);                };            }        }    });