问题描述
我有以下代码的指令
app.directive('formControl', function () {
return {
restrict: 'C',
link: function (scope, element, attrs) {
// Add class filled to form-control's that have a value
if (element.val()) {
element.parent().addClass('filled');
}
element.bind('blur', function (e) {
var input = angular.element(e.currentTarget);
if (input.val()) {
input.parent().addClass('filled');
} else {
input.parent().removeClass('filled');
}
input.parent().removeClass('active');
}).bind('focus', function (e) {
var input = angular.element(e.currentTarget);
input.parent().addClass('active');
}).bind('change',function(e) {
// Add class filled to form-control's that have a value
var input = angular.element(e.currentTarget);
input.parent().addClass('active');
} );
}
};
});
//示例指令
<div class="form-group">
<label for="lastname" class="control-label">Phone number</label>
<input type="text" class="form-control" name="phonenumber" id="phonenumber" ng-model="user.phone_number" required maxlength="75">
</div>
该指令的目的非常简单,根据少量事件和值状态向目标对象添加一些CSS类。
如果该指令没有任何值,它将正常工作。 但是如果我有一个通过模型绑定(不是从键盘,通过模型绑定)填充的值。 它不会工作。
就是 我想执行代码“ input.parent()。addClass('active');” 当指令/输入字段通过模型绑定填充值时
我尝试了更改事件,但无法正常工作
1楼
pdenes
0
2015-07-25 22:25:10
我认为您需要以某种方式掌握ng-model
设置的绑定并在模型更改时做出反应。
ng-model
公开其 ,后者又公开了模型值,您可以$watch
。
像这样:
app.directive('formControl', function () {
return {
restrict: 'C',
require: '?ngModel', // the (optional) ng-model on the same element
link: function (scope, element, attrs, ngModel) {
[...]
if (ngModel) {
scope.$watch(function() {
return ngModel.$modelValue;
}, function(newValue, oldValue) {
input.parent().addClass('active');
})
}
}
};
});