jivangilad
jivangilad

Reputation: 479

ngShow doesnt work when built inside directive

I want to add a red star to input in case it is invalid. I wrote a directive which adds a red star element near the input elemnt. I use ng-show with the star. I thought it will show only if the input is valid. The problem is, the red star always shows, even if the input is invalid.

<div ng-app="docu">
    <form name="form">
        <input name="inp" ng-error-show type="text" ng-model="x" ng-required="true">          

    </form>
</div>


var docu = angular.module('docu', ["portaldirectives"]);

var portaldirectives = angular.module("portaldirectives", []);       


portaldirectives.directive("ngErrorShow", function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ctrl) {
            var varName = "form.inp.$valid";
            element.parent().prepend('<span style="color:red" ng-show="!' + varName + '" >*</span>');
        }
    };
});

http://plnkr.co/edit/7So4ney5KEwlTaaNIN49?p=preview

Upvotes: 0

Views: 80

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77910

You must compile your new prepended element:

portaldirectives.directive("ngErrorShow", function($compile) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, ctrl) {
            var varName = "form.inp.$valid";

            var a_input = angular.element($compile('<span style="color:red" ng-show="!' + varName + '" >*</span>')(scope));

            element.parent().prepend(a_input);
        }
    };
});

Demo Fixed Plunker


Also see $comile documentation

Upvotes: 3

Related Questions