Dev Qualwebs Dev Qualwebs - 5 months ago 13
AngularJS Question

Update class of parent element by change on ngModel

I am trying to do like..,

If ng-model is not equal to blank then update the class of which is just written above of this ng-model.

I have overridden the ngModel directive by this. I am also able to get change on it by applying $watch to that ngModel. But I have stuck at this, how to get that position.

I can try ng-class to change that but I want something that can update the globally.

app.directive('ngModel', function($http ,$parse) {
return {
restrict: 'A',
scope: {
model: '=ngModel'
},
link: function(scope, element, attrs) {
scope.$watch("model", function() {
console.log(scope.model);
});
}
}
});


This is example HTML. Here I am trying to change that span class by detecting change on its model.

<span class="input">
<input class="input__field" ng-model="example" required="" type="text">
</span>

Answer

Try utilizing element argument of the link function like below

app.directive('ngModel', function($http ,$parse) {
    return {
        restrict: 'A',
        scope: {
            model: '=ngModel'
        },
        link: function(scope, element, attrs) {

            scope.$watch("model", function() {
                element.parent()[0].className='Your class name'
                console.log(scope.model);
            });
        }
    }
});