Skip to content

Instantly share code, notes, and snippets.

@masimplo
Created February 9, 2016 19:11
Show Gist options
  • Select an option

  • Save masimplo/95822e3566be25394dd3 to your computer and use it in GitHub Desktop.

Select an option

Save masimplo/95822e3566be25394dd3 to your computer and use it in GitHub Desktop.
Default angular
<div ng-app="app">
<section ng-controller="MainController as ctrl">
{{ctrl.hello}}
<input ng-model="ctrl.inputValues" cv-list />
{{ctrl.inputValues}}
</section>
</div>
let app = angular.module('app', []);
class MainController {
public hello:string = 'Hello';
public inputValues = ['hi', 'hey', 'bye'];
}
app.controller('MainController', MainController);
function myDirective(){
return {
restrict: 'A',
priority: 100,
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (angular.isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
angular.forEach(viewValue.split(','), (value) => {
if (value) list.push(value);
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (angular.isArray(value)) {
return value.join(',');
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
}
app.directive('cvList', myDirective);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment