0

I want to make custom angular directive for placeholder.

The code for the directive is as follows:

class customDirective {

restrict: string = "A";
link = (scope: ng.IScope,
    instanceElement: ng.IAugmentedJQuery,
    instanceAttributes: ng.IAttributes,
    controller: any,
    transclude: ng.ITranscludeFunction) => {
    instanceElement.val((<any>instanceAttributes).tsplaceholder);
    instanceElement.on("focus", (eventObj: JQueryEventObject) => {
        if (instanceElement.val() === (<any>instanceAttributes).tsplaceholder) {
            instanceElement.removeClass("gray-textbox");
            instanceElement.val("");
        }
    });

    instanceElement.on("blur", (eventObj: JQueryEventObject) => {
        if (instanceElement.val() === "") {
            instanceElement.addClass("gray-textbox");
            instanceElement.val((<any>instanceAttributes).tsplaceholder);
        }
    });
    instanceElement.addClass("gray-textbox");
    //instanceElement.attr("value", (<any>instanceAttributes).tsplaceholder);
    //this.$compile(instanceElement.contents())(scope);
}

}

taxSimpleApp.directive("tsplaceholder", () => {
return new customDirective();
});

I am using below html code.

<input name="ssn2"
      id="jenish"
      type="text"
      required                               
      ng-model="myVal" 
      tsplaceholder="XXX-XX-XXXX">

I am using angular with typescript.

but in above example when first view loads it does set the value property to the placeholder we pass. but after the first focus lost it suddenly starts working.

I don't have any idea why value("XXX-XX-XXXX") doesn't appear on first time.

Thanks in advance for any kind help if possible.

1 Answer 1

1

instanceElement.on is a jquery command-> at the end of it's callback run $scope.$apply() to alert Angular of changes in the model

You should also be using your ng-model "$scope.myVal", rather than instanceElement.val() to assign values to your input

Sign up to request clarification or add additional context in comments.

4 Comments

Hello koolunix thanks for the great solution I applied to my app and it worked.!
@kookunix , I did checked this inside the focus handler and it gets started but If I would do same thing inside link function than it throws error $digest already in progress.
I am writing this thing inside the link function because I want it to be set first time as "XXX-XX-XXXX".
For what you are doing I would check out "ui-mask"-> angular-ui.github.io/ui-utils/#/mask

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.