Created
November 25, 2014 15:03
-
-
Save jessehouchins/c073565f6b693877191a to your computer and use it in GitHub Desktop.
An Angular directive that converts ngModel attributes to dot notation so nested properties will bind correctly, even if they did not previously exist.
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
// convert `ng-model="foo[bar.key][baz.key]"` to `ng-model="foo.barKey.bazKey"` | |
// which will allow the ng-model directive to auto-generate the nested structure. | |
.directive('ngModelCreate', function(_){ | |
function makeDotPath(scope, expr) { | |
var pathParts = _.compact(expr.split(/\[|\]/g)) | |
var convertedParts = _.map(pathParts, function(part, i) { | |
if (i === 0) return part | |
if (part[0] === '.') return part.substr(1) | |
return scope.$eval(part) | |
}) | |
return convertedParts.join('.') | |
} | |
return { | |
restrict: 'A', | |
priority: 2, // compile before ngModel | |
scope: true, | |
controller: function($scope, $attrs, $element) { | |
var expression = $scope.expression = $scope.expression || $attrs.ngModel | |
var dotPath = makeDotPath($scope.$parent, expression) | |
$element.attr('ng-model', $attrs.ngModel = dotPath) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment