Skip to content

Instantly share code, notes, and snippets.

@iamgoangle
Last active December 26, 2015 16:09
Show Gist options
  • Select an option

  • Save iamgoangle/75f7c7241675fae65648 to your computer and use it in GitHub Desktop.

Select an option

Save iamgoangle/75f7c7241675fae65648 to your computer and use it in GitHub Desktop.
AngularJS $parsers and $formatters
<script>
/*
Definition
$parsers/$formatters are an array of actions that take in input,
translate it to either the computer-friendly or human-friendly format respectively
and return the translated value.
Formatters change how model values will appear in the view.
Parsers change how view values will be saved in the model.
*/
var testApp = angular.module('testApp', []);
testApp.controller('testCtrl', ['$scope', function($scope){
//$scope.myModel = [];
}]);
testApp.directive('tagList', function(){
return {
restrict: 'A',
require: 'ngModel',
scope: {
ngModel: '='
},
link: function(scope, iElement, iAttrs, ngModelCtrl){
//var toView = function (val) {
// return (val || []).join(', ');
//};
//var toModel = function (val) {
// return (val || '').split(',').map(function (v) {
// return v.trim();
// });
//};
//ngModelCtrl.$formatters.unshift(toView);
//ngModelCtrl.$parsers.unshift(toModel);
// to view
ngModelCtrl.$formatters.push(function(value){
return (value || []).join(', ');
})
// to model
ngModelCtrl.$parsers.push(function(value){
return (value || '').split(',').map(function (v) {
return v.trim();
});
});
}
}
});
</script>
<body ng-controller="testCtrl">
<strong>Model value</strong>
<div>{{myModel}}</div>
<strong>View value</strong>
<input type="text" ng-model="myModel" tag-list>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment