1

1 レベルのナビゲーション/メニューの場合は、"localhost/#/user" のような URL

私は使用できることを知っています

<ul>
  <li ng-class="{active: isActive('/user')}><a href="#/user'>User</a></li>
</ul>

そしてコントローラーで

$scope.isActive = function (path) {
  if ( path == $location.path() )
    return true;
  return false;
};

url が「localhost/#/user」の場合、「active」が追加されます。

それでも、2 レベルのメニューになると、「localhost/#/user/orders」のような URL

<ul>
  <li>
    <a href="#/user'>User</a>
    <ul>
      <li><a href="#/user/orders'>Orders</a></li>
    </ul>
  </li>   
</ul>

URLに基​​づいてアイテム「注文」とその親「ユーザー」の両方に「アクティブ」クラスを追加するにはどうすればよいですか? (両方をハイライトできるように)

前もって感謝します。


アップデート:

ありがとう、それは今働いています:D

@Nikos Paraskevopoulos、@piatek、@Chandermaniありがとう

コードは十分ではありませんが、CoffeeScript で書かれた私の最終的な作業コードは次のとおりですが、動作します:)

.directive('highlightActive', () ->
    return {
        restrict: "A"
        controller: [
            '$scope', '$element', '$attrs', '$location'
            ($scope, $element, $attrs, $location) ->
                links = $element.find('a')
                path = () ->
                    return $location.path()

                highlightActive = (links, path) ->
                    path = '#' + path

                    angular.forEach(links, (link) ->
                        $link = angular.element(link)
                        $li = $link.parent('li')
                        href = $link.attr('href')

                        if ($li.hasClass('active'))
                            $li.removeClass('active')
                        if path.indexOf(href) is 0
                            $li.addClass('active')
                    )

                highlightActive(links, $location.path())

                $scope.$watch(path, (newVal, oldVal) ->
                    if newVal is oldVal
                        return
                    highlightActive(links, $location.path())
                )
        ]

    }
)
4

3 に答える 3

1

これを行う方法はたくさんありますが、角型はとにかく HTML を強化する傾向があるため、一番上の要素にディレクティブを追加するだけです。

<ul activeli>
  <li>
    <a href="#/users">User</a>
    <ul>
      <li>
        <a href="#/users/orders/">Orders</a>
      </li>
      <li>
        <a href="#/users/account/">Account</a>
      </li>
    </ul>
  </li>
</ul>

App.directive('activeli', function ($location) {
  return function ($scope, $el) {
    var links = $el.find('a'),
        path = function(){ return $location.path(); }

    function addActiveClass (links, path) {
        angular.forEach(links, function (link) {
            var $link = angular.element(link);

            if ($link.hasClass('active')) {
                $link.removeClass('active');
            } else if (link.hash === ('#' + path)) {
                $link.addClass('active');
            }
        });
    }

    // Initial state
    addActiveClass(links, $location.path());

    $scope.$watch(path, function (newValue, oldValue) {
        if (newValue === oldValue) return;
        addActiveClass(links, $location.path());
    });
  };

});
于 2013-10-21T12:16:15.647 に答える