我有以下html工作,并在使用$ dirty更改输入时更改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>
然而,当我尝试将其转换为指令时,它的ng-class部分停止工作。任何人都可以帮助我让它运作吗?
指令:
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>
答案 0 :(得分:4)
这是一个掠夺者: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);
};
}
};
});