使用NG-CLICK更改单击元素上的类

时间:2016-10-26 15:25:27

标签: javascript angularjs wordpress

我正在使用通过WordPress REST-API加载的Ajax数据创建动态标签。一切正常,但我需要在活动选项卡中添加一个类,以便对其使用CSS转换。

我将不胜感激任何建议。我知道如何在单击一个元素时影响另一个元素时使用ng-class,但不会影响单击的元素。值得注意的是我正在使用ng-controller的'as'语法。

JAVASCRIPT:

  var homeApp = angular.module('homeCharacters', ['ngSanitize']);
homeApp.controller('characters', function($scope, $http) {
  $scope.myData = {
    tab: 0
  }; //set default tab
  $http.get("http://bigbluecomics.dev/wp-json/posts?type=character").then(function(response) {
    $scope.myData.data = response.data;
  });
});
homeApp.filter('toTrusted', ['$sce',
  function($sce) {
    return function(text) {
      return $sce.trustAsHtml(text);
    };
  }
]);
HTML:

<div class="more_comics_mobile"><a href="javascript:void(0)">More Comics <img src="./images/white-arrow.png" /></a>
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
  <div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
    {{ item.content }}
  </div>
  <div class="char_tabs">
    <nav>
      <ul ng-init="myData.tab = 0" ng-model='clicked'>
        <li class="tab" ng-repeat="item in myData.data">
          <a href ng-click="myData.tab = item.menu_order">
            <img src="{{ item.featured_image.source }}" />
            <h3>{{ item.title }}</h3>
          </a>
        </li>
      </ul>
    </nav>
  </div>
</section>

我正在尝试将该类添加到li元素中。我感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

您可以使用ng-class之类的

<li class="tab" ng-repeat="item in myData.data" ng-class="{'active' : item.menu_order == myData.tab}"></li>

您可以访问更多选项 https://docs.angularjs.org/api/ng/directive/ngClass

答案 1 :(得分:0)

<div class="more_comics_mobile"><a href="javascript:void(0)">More Comics <img src="./images/white-arrow.png" /></a>
</div>
<section class="characters" ng-app="homeCharacters" ng-controller="characters as myData">
  <div class="char_copy" ng-repeat="item in myData.data" ng-bind-html="item.content | toTrusted" ng-show="myData.tab === item.menu_order">
    {{ item.content }}
  </div>
  <div class="char_tabs">
    <nav>
      <ul ng-init="myData.tab = 0" ng-model='clicked'>
        <li class="tab" ng-click="activate($index)" ng-repeat="item in myData.data">
          <a href ng-click="myData.tab = item.menu_order">
            <img src="{{ item.featured_image.source }}" />
            <h3>{{ item.title }}</h3>
          </a>
        </li>
      </ul>
    </nav>
  </div>
</section>

在你的js中

$scope.activate = function(index){
       document.getElementsByClassName.setAttribute("class","tab");

       document.getElementsByClassName[index].setAttribute("class","tab active");
}