AngularJS templates can't use JSON that contains hyphen

All we need is an easy explanation of the problem, so here it is.

AngularJS templates can’t use JSON that contains hyphen in the key.

e.g.

My Json looks like

{
   ...
   link: {
       xx-test:{
            href: '/test/xx'
         }
}

Now, in my angularjs template if I refer the href it is not working

<a ng-href="/app/edit?item={{item.link.xx-test.href}}" rel="nofollow noreferrer noopener"></a>

It is unable to resolve the value href is rendered as
/app/edit?item=

It tried

<a ng-href="/app/edit?item={{'item.link.xx-test.href'}}" rel="nofollow noreferrer noopener"></a>
<a ng-href="/app/edit?item={{item.link.xx\-test.href}}" rel="nofollow noreferrer noopener"></a>
<a ng-href="/app/edit?item={{item.['link.xx-test'].href}}" rel="nofollow noreferrer noopener"></a>

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The object key needs to be quoted with:

$scope.bar = {'xx-test':'foo'};

Bracket notation should be used in the angular expression.

<p>{{bar['xx-test']}}</p>

You can optionally escape the hyphen \- in the angular expression.

Method 2

try {{item.link[‘xx-test’].href}}

For further reading on bracket notation:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply