Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dash-case to camelCase in AngularJS?

Tags:

angularjs

Is there any utility function in AngularJS that converts a dash-case string to a camelCase string? e.g.: "min-max" becomes "minMax"

That's quite simple to implement my own function:

function toCamelCase(name) {
  return name.replace(/-(\w)/g, function(match) {
    return match[1].toUpperCase();
  });
}

But, I know that Angular already does this (e.g. directive name), so I wonder if it's possible to use the mechanism that Angular has?

like image 841
Misha Moroshko Avatar asked Jun 23 '14 01:06

Misha Moroshko


People also ask

What is camel case in JavaScript?

Camel case is the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. For example, Concurrent hash maps in camel case would be written as − ConcurrentHashMaps.


2 Answers

You can access to angular's camelCase function inside of a directive:

link: function (scope, element, attrs) {
  attrs.$normalize('ng-model'); // ngModel
  attrs.$normalize('ng:click'); // ngClick
  attrs.$normalize('ng_show'); // ngShow
}

Best!

like image 102
marian2js Avatar answered Oct 02 '22 16:10

marian2js


In angular this is part of jqlite, the minimalistic jquery implementation that they're using internally. I don't think there's a way of accessing that because I believe it's private. This is the function though:

function camelCase(name) {
  return name.
    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
      return offset ? letter.toUpperCase() : letter;
    }).
    replace(MOZ_HACK_REGEXP, 'Moz$1');
}

Where

var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
like image 31
Jorg Avatar answered Oct 02 '22 16:10

Jorg