角度ng-单击不在ng-repeat中工作

时间:2015-03-15 13:11:28

标签: javascript angularjs angularjs-ng-repeat angularjs-ng-click

我正在尝试使用ng-click中的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

我哪里错了?

1 个答案:

答案 0 :(得分:3)

我认为在更改ng-repeat中的显示值时你没有正确使用,因为ng-repeat创建了自己的范围。除此之外,您应该绑定一个函数来设置$ scope.showing的值。 例如:


    $scope.changeShowing = function(img) {
        `$scope.showing = img;`
    };

ng-click =&#34; changeShowing(img)&#34;&#39;