0

If i have a property with a dash, lets say a-a with the value of 'some value' on my scope, and i try to evaluate

scope.$eval('a-a')

it will return 0. I suppose it thinks that the hyphen is a subtraction operator, but anyhow: is there a way to call $eval that will return what i need (i.e. 'some-value')?

This fiddle shows the example:http://jsfiddle.net/BusD7/1/

kamilkp
  • 9,690
  • 6
  • 37
  • 56

1 Answers1

0

There are a few issues with what you are trying to do here.

In your fiddle, you have

$scope['a-a'] = 'some value';

The first issue is that 'a-a' is NOT a correct variable name. JS variables can have underscores(_), alpha-numeric(a-z,1-9), and dollar-signs($) You are trying to create a variable with a hyphen(-); this is not allowed in JS.

See this doc. JS variable names

Secondly, in your jsFiddle you have

{{$eval('a-a')}}

The Angularjs $eval function is trying to make sense of the EXPRESSION you provided 'a-a', and yes the $eval function is trying to evaluate the - operator.

See here for an example:

Angularjs Expressions

That is what Angular is doing when you just do this

{{ a-a }} which will result in 0 as well.

and {{ 'a-a' }} would just result in a string of a-a

Play around on your jsFiddle and you will see what it does.

To answer your question, do this to get it to work.

 $scope['a-a'] = 'some value';    to this    $scope['a_a'] = 'some value'; 

and

{{$eval('a-a')}}        to this      {{$eval('a_a')}}

Now that you know variable names cannot have hyphens (in JS), what exactly are you trying to accomplish, and I will assist getting you there.

UPDATE:

Yes of course, thank you for the correction. You are creating an object property using bracket notation. I mostly keep to dot notation (even when using bracket notation ), and dot noation only allows normal variable names.

Here is a link to both notation types

An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.

and link Bracket Notation Information

To solve your issue using Angularjs please do the following:

Add your 'a-a' property name to a new object and attach to $scope.

like this: $scope.myNewObject = {};
           $scope.myNewObject['a-a'] = 'some value';

Then call it like this:
           {{ myNewObject['a-a'] }}

Will return: some value

Here is the idea working in a jsFiddle

Working Answer Link

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • While i agree that `The first issue is that 'a-a' is NOT a correct variable name` it IS a correct **property** name. And in that example 'a-a' is not a variable but a property on $scope. – kamilkp Feb 05 '15 at 11:03