I'm new to using angular and I'm having a hard time with writing directives. In particular I wish to write one that displays floats as percentage in the view. I would like the behaviour to be as follow: When the view loads and data is being read from the controller I want the directive to display the corresponding float-property as percentage (i.e. 0.25 -> 25%). When the user inputs an integer into the input-field I'd like it to be shown as percentage on the blur-event (i.e. 10 -> 10%). Here's my code so far:
restrict = "A";
require = "ngModel";
scope = {
ngModel: "="
}
constructor( /* list of dependencies */) {
}
link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ngModel: ng.INgModelController /*ctrl: any*/): void => {
// handle linking requirements (?)
element.on("onload", (): void => {
var modelValue = ngModel.$modelValue;
var viewValue = this.toViewValue(modelValue);
ngModel.$setViewValue(viewValue);
ngModel.$render();
});
element.on("blur", (): void => { // lambda to handle this-scope
var viewValue = ngModel.$viewValue;
viewValue = this.toViewValue(viewValue);
ngModel.$setViewValue(viewValue);
ngModel.$render();
});
}
private toModelValue(val: string): number {
return 0;
}
private toViewValue(val: string): string {
var str = val.replace("%","").trim();
if (this.isInteger(str)) {
var i = parseInt(str);
if (i >= 100) {
str = "100";
}
} else if (this.isFloat(str)) {
var f = parseFloat(str);
str = (f * 100).toString();
}
return str + "%";
}
private isInteger(val: any): boolean {
return val.match(/^[0-9]{1,3}$/);
}
private isFloat(val: any): boolean {
return val.match(/^\d(\.\d{1,2})?$/);
}
Here's the input-field I'm applying my directive to:
<div class="form-group">
<label for="payment-interest-rate" class="col-sm-4 control-label"></label>
<div class="col-sm-8">
<input type="text" class="form-control" data-percent id="payment-interest-rate" name="paymentInterestRate" data-ng-model="ctrl.economicInfo.paymentInterestRate"
data-ng-model-options="{updateOn: 'blur'}">
</div>
</div>
And here's how I register it with my module:
.directive("percent", MyApp.Core.Directives.DisplayPercentageDirective.create)
As you cansee I'm using TypeScript and I'm having a bit of difficulty in finding relevant examples because of this. I'm using what I believe is refered to as a Directive Factory pattern(?) The blur-event works without problem however I'm struggling to trigger the directive when the template first loads. What am I doing wrong?
Regards Kristofer