我试图根据条件在指令内动态地将类添加到输入标签。像这样:
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, model) {
model.$render = function () {
if (verify(model.$modelValue)) {
var elm = getElm(element)
elm.addClass('default');
}
}
}
但是,如果element是输入,则该值不会显示在视图中。
有人猜到我在做什么错吗?
答案 0 :(得分:1)
更新
根据注释中更新的要求,我们可以添加异步验证器来添加类。
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.test = "asdf";
})
.directive('checkAvailability', function checkAvailabilityFunc($q) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$asyncValidators.userExist = function(modelValue, viewValue) {
var deferred = $q.defer();
if (modelValue === 'asdf') {
element.parent().addClass('default');
deferred.resolve();
} else {
element.parent().removeClass('default');
deferred.reject();
}
return deferred.promise;
}
}
}
});
.default {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.2/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<div style="padding:10px;display:inline-block;">
<input type="text" ng-model="test" check-availability>
</div>
</div>
我不确定您为什么要为此而去复杂的$render
,请检查下面的示例,我们可以在其中使用ng-class
并达到相同的目的。要了解有关ng-class
的更多信息,请访问here
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.test = "asdf";
});
.default {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<input type="text" ng-model="test" ng-class="{ 'default' : test === 'asdf' }">
</div>