如何在模型绑定后重新运行指令的link函数

How to re -run the link function of directive after model binding

本文关键字:指令 link 函数 重新运行 模型 绑定      更新时间:2023-09-26

我有以下代码指令

 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类。

如果没有任何值,这个指令也可以正常工作。但是如果我有一个通过模型绑定填充的值(不是通过键盘,而是通过模型绑定)。这行不通。

Ie。我想执行代码"input.parent().addClass('active');"当指令/输入字段通过模型绑定填充值

我尝试了更改事件,但它不工作

我认为您需要的是以某种方式获得ng-model设置的绑定,并在模型更改时做出反应。ng-model暴露了它的NgModelController,它反过来暴露了模型值,你可以$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');
                })
            }
        }
    };
});