Skip to content

Instantly share code, notes, and snippets.

@jessehouchins
Created November 25, 2014 15:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jessehouchins/c073565f6b693877191a to your computer and use it in GitHub Desktop.
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.
// 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