Evik James Evik James - 3 months ago 6
AngularJS Question

How to reference divs by class by index in AngularJS?

I am new to AngularJS. This is my first Plunker.

I am trying to make it so that if a user clicks on a link in a section, the value of the link appears in the results. The other two results should be cleared of their values.

I can't find any documentation on how to reference specific items in a class by index. In jQuery, I would normally do something like...

// get this index of the thing that was clicked
$this = $(this),
Idx = $BUTTONS.BigButtons.index($this),
ThisButton.eq(Idx).doSomething();



<body ng-controller="MainController as main">

<div class="title" ng-repeat="i in [1,2,3]">
<p>This is section {{i}}</p>
<ul>
<li ng-repeat="j in [1,2,3]">
<a href="" ng-click="main.displayContent(i, j)">section {{i}} - link {{j}}</a></li>
</ul>
<div class="results" ng-bind="main.results"></div>
</div>
</body>


var app = angular.module('controllerAsDemo', []);
app.controller('MainController', function() {

this.results = "Lame default";

this.displayContent = function(firstIdx, secondIdx) {

this.results = "populate section "
+ firstIdx
+ " with the number "
+ secondIdx
+ " - other two results should be empty"
;

};

});


Here is the Demo

Answer

I think you should not be looking at classes to achieve what you want. Angular repeat and various other directives give you the ability to do that.

I have touched your code a little and it works now. See below.

var app = angular.module('controllerAsDemo', []);

app.controller('MainController', function($scope) {

  $scope.name = 'Cool Clicking';

  $scope.results = [];
  
    $scope.displayContent = function(firstIdx, secondIdx) {
    $scope.results = [];
    $scope.results[firstIdx] = "populate results " 
      + firstIdx
      + " with the number "
      + secondIdx
      + " - other two results should be empty"
      ;

  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

  <body ng-app="controllerAsDemo" ng-controller="MainController as main">

    <p>{{main.name}}!</p>

    <!-- LOOP THROUGH A GALLERY THEME -->
    <div class="title" ng-repeat="i in [1,2,3]">

      <p>This is section {{i}}</p>

      <ul>
          <li ng-repeat="j in [1,2,3]">
            <a href="" ng-click="displayContent(i, j)">section {{i}} - link {{j}}</a>
          </li>
      </ul> 

      <div class="results" ng-bind="results[i]"></div>

    </div> 

</body>

That said, if you want to use jQuery in Angular then you simply can. I will suggest you read about Angular Dom Manupulation here