如何在AngularJS中按索引引用div?

时间:2016-08-18 14:55:06

标签: angularjs

我是AngularJS的新手。这是我的第一个Plunker。

我正在努力使其如果用户点击某个部分中的链接,则链接的值会显示在结果中。其他两个结果应该清除它们的值。

我找不到任何关于如何通过索引引用类中特定项的文档。在jQuery中,我通常会做类似的事情......

// 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"
  ;

};

});

以下是 Demo

1 个答案:

答案 0 :(得分:1)

我认为你不应该看课程来实现你想要的。角度重复和各种其他指令使您能够执行此操作。

我已经触及了你的代码,它现在有效。见下文。

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>

那就是说,如果你想在Angular中使用jQuery那么你就可以了。 我建议你阅读Angular Dom Manipulation here

另一种方法可以在this plunkr中看到,其中图库中的每个项目都有他的结果。