简体   繁体   中英

AngularJS How do I access JSON from a directive

I have written the following directive:

var gameOdds = function(){
    return {
        template: '{{games["@homeTeam"]}} vs {{games["@awayTeam"]}}',
        scope: {
            games: '@'
        }
    };
};

<div game-odds games="{{games}}">

This uses the following JSON data (part of the json is below):

{
    @id: "69486",
    @homeTeam: "Home Team",
    @awayTeam: "Away Team",
    otherNormalValues : {
        etc: "normal..."
    }
}

I know that the method of selecting these keys preceded with an @ symbol works when put directly into the HTML bound to a controller. But in my directive I cannot select the fields in this ["@field"] way.

Does anyone know how to do this?

Instead of using the attribute object notation, @ , you can use the = instead.

DEMO

JAVASCRIPT

  .directive('gameOdds', function() {
    return {
      template: '{{games.homeTeam}} vs {{games.awayTeam}}',
      scope: {
        games: '='
      }
    }
  });

HTML

<div game-odds games="games"></div>

Update: Sorry for the late reply, as what the accepted answer had mentioned, you can access them with the [] notation, if the key starts with special characters in it:

  .directive('gameOdds', function() {
    return {
      template: '{{games['@homeTeam']}} vs {{games['@awayTeam']}}',
      scope: {
        games: '='
      }
    }
  });

The @ symbol on scope transforms whatever you pass to the attribute games into text, and passes it into your directive. If you use the = symbol, you can pass a scope variable into the directive.

With @ , scope.games will be a string

With = , scope.games will be your json object

var gameOdds = function(){
    return {
        template: '{{games["@homeTeam"]}} vs {{games["@awayTeam"]}}',
        scope: {
            games: '='
        }
    };
};

<div game-odds games="games">

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