0

I'm trying to save an array element in another variable using ng-click in ng-repeat, but when I click the element, it doesn't work.

This is my Code:

<!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>

This is my 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 = {};
});

There is my complete code: http://jsbin.com/fuyuci/1/edit

Where I was wrong?

7
  • what do you want to do here <a ng-click="index = img">{{img.descricao}}</a>? Commented Mar 15, 2015 at 13:16
  • sorry, I edited my code Commented Mar 15, 2015 at 13:18
  • 2
    Try this : jsbin.com/mevafajifu/1 ? Commented Mar 15, 2015 at 13:21
  • 2
    ngRepeat create own scope, so when you assign variable - it assign to ngRepeat scope, also yet another way for solving use $parent like $parent.showing = img Commented Mar 15, 2015 at 13:26
  • 1
    Refer this post: stackoverflow.com/questions/15623698/… . It will clear your doubts Commented Mar 15, 2015 at 13:30

1 Answer 1

3

I think that you're using not correctly when changing value of showing in ng-repeat because ng-repeat create own scope. In stead of that, you should bind an function to set value for $scope.showing. for example:


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

ng-click ="changeShowing(img)"'

Sign up to request clarification or add additional context in comments.

1 Comment

rly helpfull ;) didn't know that ng-repeat creats there own scope

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.