我遇到以下问题,但找不到解决方案。
这是我当前的 Angular JS 文件:
(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"
}
]
}
通过以下调用从 JSON 获取数据没有问题:
{{ heroes.cw[0].name }}
{{ heroes.cw[0].type }}
{{ heroes.cw[0].roles }}
我需要使用一个变量,这样我就可以用从 ng-click 获得的缩写替换 cw。
<div title="Clockwerk" ng-click="selectHero(heroes.cw[0].abbr)"></div>
我正在尝试使用 ng-click 的函数来完成此任务:
$scope.selectHero = function(selectedHero) {
$scope.name = heroes.selectedHero[0].name;
};
现在应该在 {{ name }} 中显示 Clockwerk,但它不起作用。我有什么遗漏的吗?
基本上我想保留 {{ Heroes.x[0].name }} ,并且 x 应该替换为我从 ng-click 中的函数获得的值(在本例中为“cw”)。
最佳答案
使用[]
对象表示法,可以在大括号之间传递变量
$scope.name = heroes[selectedHero][0].name;
关于javascript - 使用 ng-click 更改 JSON 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456248/