Skip to content

Instantly share code, notes, and snippets.

@jessehouchins
Created February 28, 2015 23:44
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 jessehouchins/7052fdf2af923416dc37 to your computer and use it in GitHub Desktop.
Save jessehouchins/7052fdf2af923416dc37 to your computer and use it in GitHub Desktop.
Null ng-false-value
;(function(){
'use strict'
// Sets falsy values as null on the model. This does not seem to be possible
// using ng-false-value, since it sets it as "null" (string) instead.
// usage <input type="checkbox" ng-model"model.attr" null-false-value />
angular.module('yourModule')
.directive('nullFalseValue', function(_){
return {
require: 'ngModel',
link: function(scope, el, attrs, ctrl){
var ngModel = ctrl
var parserSet
function parser(inputVal){
return inputVal || null
}
function setParser() {
if (!parserSet) parserSet = ngModel.$parsers.push(parser)
}
// Angular 1.2 runs the input directive logic in a post-link function...
// since ngModel requires the input directive, and we require ngModel,
// there is no way to run our $parser after the input directive $parser.
// so the (gulp) hack is to insert it on the first change/focus event.
el.one('focus', setParser)
el.one('change', setParser)
}
}
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment