【发布时间】:2015-03-16 00:07:25
【问题描述】:
我正在尝试使用 ng-repeat 中的 ng-click 将数组元素保存在另一个变量中,但是当我单击该元素时,它不起作用。
这是我的代码:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="myCtrl">
<div ng-repeat="img in images">
<a ng-click="showing = img">{{img.descricao}}</a>
</div>
--------------------
Clicked element description is: {{showing.descricao}}
</body>
</html>
这是我的javascript:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.images = [
{
"id": 1,
"image": "http://placehold.it/300x300",
"ordem": 1,
"descricao": "Descricao 1"
},
{
"id": 2,
"image": "http://placehold.it/300x300",
"ordem": 2,
"descricao": "Descricao 2"
}
];
$scope.showing = {};
});
有我的完整代码:http://jsbin.com/fuyuci/1/edit
我哪里错了?
【问题讨论】:
-
你想在这里做什么
<a ng-click="index = img">{{img.descricao}}</a>? -
对不起,我编辑了我的代码
-
试试这个:jsbin.com/mevafajifu/1?
-
ngRepeat创建自己的范围,因此当您分配变量时 - 它分配给 ngRepeat 范围,这也是解决使用$parent像$parent.showing = img的另一种方法 -
参考这篇文章:stackoverflow.com/questions/15623698/…。它会清除你的疑虑
标签: javascript angularjs angularjs-ng-repeat angularjs-ng-click