Created
February 28, 2015 23:44
-
-
Save jessehouchins/7052fdf2af923416dc37 to your computer and use it in GitHub Desktop.
Null ng-false-value
This file contains 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
;(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