Skip to content

Instantly share code, notes, and snippets.

@pmoelgaard
Created February 26, 2016 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmoelgaard/5f77b8804e91bfb9440e to your computer and use it in GitHub Desktop.
Save pmoelgaard/5f77b8804e91bfb9440e to your computer and use it in GitHub Desktop.
/// <reference path="../../typings/tsd.d.ts" />
/// <reference path="../tsd.d.ts" />
module nx.ui.modelFormatter {
var $module:ng.IModule = angular.module('nx.ui');
export interface IModelFormatterScope extends ng.IScope {
}
export function ModelFormatterDirectiveLinkFn($scope:IModelFormatterScope,
$element:any,
$attrs:ng.IAttributes,
controllers:Array<any>) {
var ngModelCtrl:ng.INgModelController = controllers[0];
ngModelCtrl.$formatters.push(function (modelValue:string) {
var formatterExp:string = <string>_.get($attrs, 'nxModelFormatter');
var formatterFn:Function|Array<string> = $scope.$eval(formatterExp) || eval(formatterExp);
if (_.isFunction(formatterFn)) {
modelValue = formatterFn.call(modelValue);
}
else if (_.isArray(formatterFn)) {
_.each(formatterFn, function (formatterExp:string):any {
var formatterFn:Function = _.attempt(function ():any {
return $scope.$eval(formatterExp) || eval(formatterExp);
});
modelValue = _.isFunction(formatterFn) ? formatterFn(modelValue) : _.invoke(modelValue, formatterExp);
});
}
return modelValue;
});
}
function ModelFormatterDirective():ng.IDirective {
var definition = {
restrict: 'A',
require: ['ngModel'],
link: ModelFormatterDirectiveLinkFn
};
return definition;
};
ModelFormatterDirective.$inject = [];
$module.directive('nxModelFormatter', ModelFormatterDirective)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment