Reputation: 6766
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.
Upvotes: 0
Views: 714
Reputation: 1995
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
Upvotes: 1