简体   繁体   中英

AngularJS - Double curly brackets causing Syntax Error

I am trying to print out the $index of ng-repeat, but it gives me:

Error: [$parse:syntax] Syntax Error: Token '{' is an unexpected token at column 8 of the expression [markers{{ $index }}] starting at [{{ $index }}].

This is my code:

<div ng-repeat="place in places">
         <leaflet id="map{{ $index }}" defaults="defaults" center="center" markers="markers{{ $index }}"></leaflet>
</div>

But changing to this works:

<div ng-repeat="place in places">
     <leaflet id="map{{ $index }}" defaults="defaults" center="center" markers="markers0"></leaflet>

This is very strange...why does that happen?

Look at the directive of leaflet it does have = form markers, See this code

= means you enabaled to way binding inside your isolated, for that you must have provide scope variable reference in that attribute.

Where markers0 does work because you provided the scope reference,

But when you provide {{}} interpolation in that attribute will get failed as you are doing like markers="markers{{ $index }}"

For handle this issue elegantly i would prefer you to create one array of markers that will have multiple values you that the data will become like this

$scope.markers = [{...},{...},{...},...] 

instead of

$scope.marker0 = {}, $scope.marker1 = {}, $scope.marker2 = {}, ....

So that you could easily point to that from using its $index

Markup

<div ng-repeat="place in places">
    <leaflet id="map{{ $index }}" defaults="defaults" center="center" 
     markers="markers[$index]"></leaflet>
</div>

I've encountered a similar issue but with a different directive. One work around I did was actually placing a single quote before and after the curly brackets

 <div ng-repeat="place in places">
     <leaflet id="map{{ $index }}" defaults="defaults" center="center" markers="markers'{{ $index }}'"></leaflet>
 </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM