user2904935
user2904935

Reputation:

Change JSON call with ng-click

I have the following problem and I just can't find a solution.

This is my current JS file for Angular:

(function() {

    var app = angular.module("dota2impetus", [ ]);

    app.controller("heroGuide", ["$scope", "$http", function($scope, $http) {

        $scope.heroes = [ ];

        $http.get("js/custom/heroes.json").success(function(data) {
            $scope.heroes = data;
        });

    }]);

})();

JSON:

{
    "cw": [
        {
            "name": "Clockwerk",
            "abbr": "cw",
            "type": "r-str-big",
            "roles": "Initation, Durable"
        }
    ]
}

I have no problem getting the data from my JSON with the following calls:

{{ heroes.cw[0].name }}
{{ heroes.cw[0].type }}
{{ heroes.cw[0].roles }}

I need to use a variable though so I can replace cw with the abbreviation I get from ng-click.

<div title="Clockwerk" ng-click="selectHero(heroes.cw[0].abbr)"></div>

I am trying to accomplish this with the function from ng-click:

$scope.selectHero = function(selectedHero) {
    $scope.name = heroes.selectedHero[0].name;
};

It should now display Clockwerk in {{ name }} but it won't work. Is there anything I'm missing?

Basically I want to keep {{ heroes.x[0].name }} and the x should be replaced with the value I get from my function in ng-click (in this example it's "cw").

Upvotes: 1

Views: 400

Answers (1)

charlietfl
charlietfl

Reputation: 171689

Use [] object notation which lets you pass a variable between the braces

$scope.name = heroes[selectedHero][0].name;

Upvotes: 1

Related Questions