2014-02-10 20 views
2

我有以下的HTML中工作,並使用$髒時,輸入被轉換更改類的div:

<div class="text-input" ng-class="{typing : (loginForm.test.$dirty || loginForm.test.length > 0)}"> 
    <span>Username</span> 
    <input type="text" name="test" ng-model="user.name" placeholder="test"> 
    </div> 

然而,當我試圖使之成爲一個指令,對納克級的部分原因它停止工作。任何人都可以幫助我得到它的工作?

指令:

angular.module('myApp').directive('smartInputElement',function(){ 
return { 
    restrict: 'E', 
    require: 'ngModel', 
    compile: function(element, attrs) { 
    element.replaceWith('<div class="text-input" ng-class="{typing : ('+attrs.formname+'.'+attrs.name+'.$dirty || '+attrs.formname+'.'+attrs.name+'.length > 0)}">'+ 
    '<span>'+attrs.label+'</span>'+ 
    '<input type="text" name="'+attrs.name+'" ng-model="ngModel" placeholder="'+attrs.name+'"></div>'); 
    } 

} 

});

的指令的HTML是:

<smart-input-element name="username" formName="loginForm" label="Username" ng-model="username"></smart-input-element> 

回答

4

這裏是一個plunker:http://plnkr.co/edit/3AFOHZFgExZKHjnd3gb0?p=preview

當您更換編譯功能,您應該中的元素:

指令:

app.directive('smartInputElement', function($compile) { 
    return { 
    restrict: 'E', 
    priority: 1001, 
    terminal: true, 
    compile: function(tElm, attrs) { 
     var template = angular.element(
     '<div class="text-input" ng-class="{typing : (' + attrs.formname + '.' + attrs.name + '.$dirty || ' + attrs.formname + '.' + attrs.name + '.length > 0)}">' + 
     '<span>' + attrs.label + '</span>' + 
     '<input type="text" name="' + attrs.name + '" ng-model="' + attrs.ngModel + '" placeholder="' + attrs.name + '">' + 
     '</div>'); 

     tElm.replaceWith(template); 
     var fn = $compile(template); 
     return function(scope) { 
     fn(scope); 
     }; 

    } 
    }; 
}); 
+0

非常感謝您的幫助。這工作。我花了很多時間在這件事上,並沒有充分考慮問題的可能性。 –

+0

只是爲了跟進 - 伊蘭,你認爲這是做這件事的最好方式嗎?是否有另一種方法在一個指令中實現這一點,比使用編譯更好? –

+0

謝謝@Ilan – oodavid