Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active October 16, 2015 18:53
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 zachlysobey/3cb0db7f5ebcad158f0a to your computer and use it in GitHub Desktop.
Save zachlysobey/3cb0db7f5ebcad158f0a to your computer and use it in GitHub Desktop.
Hmmmmm
angular.module('my.Module').directive('dateControl', dateControl);
function dateControl() {
return {
bindToController: true,
controller: Controller,
controllerAs: 'vm',
scope: {
isDataReady: '=',
dateMilliseconds: '='
},
template: '<input type="date" ng-model="vm.dateObj">'
};
}
/* @ngInject */
function Controller($scope, $log) {
const vm = this;
onDataReady(activate);
function onDataReady(callback) {
const unbind = $scope.$watch('vm.isDataReady', isDataReady => {
if (!isDataReady) { return; }
callback();
unbind();
});
}
function activate() {
vm.dateObj = new Date(vm.dateMilliseconds);
syncDateMillisecondsWithProxy();
}
function syncDateMillisecondsWithProxy() {
$scope.$watch('vm.dateObj', (newDate, oldDate) => {
if (newDate === oldDate) { return; }
vm.dateMilliseconds = newDate.getTime();
});
}
}
@zachlysobey
Copy link
Author

I have a few different places like this, where I want to bind a control to data, but the data that the control consumes needs to be mapped into a different type.

In this example, I have a millisecond (int) value, but my control needs to consume a Date.

I can genericize this this code into a services or something, but wanted to first explore if there's a better way.

@zachlysobey
Copy link
Author

Adam posted this, which is an interesting approach:

http://jsfiddle.net/asicfr/Mp7kT/

It essentially requires the ngModel controller, and uses ngModel.$parsers and ngModel.$formatters arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment