AngularJs使用ng-click

时间:2016-06-17 13:42:11

标签: angularjs

我有链接,当路径匹配时,获取和删除一个类,工作完美,现在唯一的问题是:其中一个链接没有路径,那么如何从 link1 中删除该类点击 link2 后上面?我可以在 link2 “没有路径的人”中插入课程,所以现在我想在点击链接2后删除 link1 类。任何想法的人?

谢谢。

HTML

<div class="sidebar-nav">
  <ul>
    <li ng-class="{'current':getLocation('/url/test')}">
      <a href="#/url/test">link 1
          <i class="pull-right fa fa-calendar-plus-o" aria-hidden="true"></i>
        </a>
    </li>
    <li ng-click="current=!current" ng-class="{'current': current}" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
      <a>link 2
        <i class="pull-right fa fa-circle" aria-hidden="true"></i></span></a>
      <div class="collapse collapse-styled" id="collapseExample">
        <a href="#">sublink 1
              <i class="pull-right fa fa-calendar" aria-hidden="true"></i>
            </a>
        <a href="#">sublink 2
              <i class="pull-right fa fa-list" aria-hidden="true"></i>
            </a>
      </div>
    </li>
  </ul>
</div>

角:

angular.module('components').controller('sidebarController', [
  '$location',
  '$scope',
  'jquery',

  function($location, $scope, $) {
    'use strict';

    $scope.getLocation = function(path) {
      var Search = new RegExp('^' + path, '');
      return !!Search.exec($location.path());
    };
  }
]);

1 个答案:

答案 0 :(得分:1)

作为 Leticia 评论链接,请执行类似的操作。而不是绑定到函数,将link 1当前类条件绑定到变量。

模板:

<div class="sidebar-nav">
  <ul>
    <li ng-click="getLocation('/url/test')" ng-class="{'current': activeLinks[1]}">
      <a href="#/url/test">link 1
          <i class="pull-right fa fa-calendar-plus-o" aria-hidden="true"></i>
      </a>
    </li>
    <li ng-click="linkClicked(2)" ng-class="{'current': activeLinks[2]}" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
      <a>link 2
        <i class="pull-right fa fa-circle" aria-hidden="true"></i>
      </a>
    </li>
  </ul>
</div>

在控制器中:

$scope.activeLinks = [];

$scope.linkClicked = function(link) {
    $scope.activeLinks.length = 0;
    $scope.activeLinks[link] = true;
}

$scope.getLocation = function(path) {
    var Search = new RegExp('^' + path, '');

    // test: suppose $location.path is /url/test
    var locationPath = '/url/test';
    if(!!Search.exec(locationPath)) {
      $scope.activeLinks.length = 0;
      $scope.activeLinks[1] = true
    };
};

此处,activeLinks数组用于将current类设置为链接。如果activeLinks[1]为真,current的{​​{1}}类条件为真。如果link 1为真,activeLinks[2]的{​​{1}}类条件为真。一次只有一个链接会有当前的类,使其他链接错误。

请参阅此DEMO