簡體   English   中英

ng-select選項與自定義指令一起使用時會加倍

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

我正在嘗試實現可動態配置的字段。 我將從服務器獲取json所需的驗證規則ng-required,ng-hidden,ng-disabled等屬性,並通過指令動態設置它們。

我有以下指令代碼。 它顯示選擇值加倍,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) {
        return {
            require: '?ngModel',
            restrict: 'A',
            compile:function (t, tAttrs, transclude){
                var tElement = t.clone()  ;
                tElement.removeAttr('input-config');
                tElement.attr('ng-required',true);
                t.attr('ng-required',true);
                return function(scope){
                    // first prepare dom 
                    t.replaceWith(tElement);
                    // than compile
                    $compile(tElement)(scope);
                };
            }
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM