Last active
December 26, 2015 16:09
-
-
Save iamgoangle/75f7c7241675fae65648 to your computer and use it in GitHub Desktop.
AngularJS $parsers and $formatters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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