Search code examples
javascriptangularjsangular-directive

Angular getting Syntax Error: Token ':' is an unexpected token while accessing URLs from JSON


I have the following json and I am pulling tweeturl from it

{
  "name": "Lifehacker",
  "handle": "@lifehacker",
  "avatar": "images/lifehacker.png",
  "time": "1h",
  "tweet": "Workflow, the nifty automation app on iOS, just got a heck of a lot easier to use: ",
  "attachments": {
    "media": "image",
    "url": "images/twitter.jpg"
  },
  "tweeturl": "http://lifehac.kr/L18xlfM",
  "interaction": {
    "like": "2m",
    "retweet": "5k"
  }
}

and displaying it like this:

<a href="{{tweets.tweeturl}}" ng-show="{{tweets.tweeturl}}">{{tweets.tweeturl}}</a>

but everytime it executes I get the URL but also receive errors on console saying

Syntax Error: Token ':' is an unexpected token at column 5 of the expression [http://lifehac.kr/L18xlfM] starting at [://lifehac.kr/L18xlfM].

I am pretty new to angular any help and explanation will be appreciated


Solution

  • ng-show expects an expression (e.g. a name of a defined in the scope variable, that evaluates to truthy or falsy value), not a string.

    You don't have to interpolate it using {{ }} syntax. Just pass the variable directly:

    <a href="{{tweets.tweeturl}}" ng-show="tweets.tweeturl">{{tweets.tweeturl}}</a>
    

    When you write ng-show="{{tweets.tweeturl}}" instead, what happens is Angular first interpolates {{tweets.tweeturl}} to http://lifehac.kr/L18xlfM - and then it tries to treat it as an expression, so it's like you'd try to write a javascript like this:

    function someFunction () {
       var abc = '123';
       http://lifehac.kr/L18xlfM    // <- this is not a correct expression
       return abc;
    }