23

使用AngularJS单击元素兄弟时获取元素兄弟的惯用方法是什么?

到目前为止,我有这个:

<div ng-controller="FooCtrl">
    <div ng-click="clicked()">One</div>
    <div ng-click="clicked()">Two</div>
    <div ng-click="clicked()">Three</div>
</div>

<script>
    function FooCtrl($scope){
        $scope.clicked = function()
        {
            console.log("Clicked", this, arguments);
        };
    }
</script>

这是一个 jQuery 实现作为具体示例:

<div id="foo">
    <div>One</div>
    <div>two</div>
    <div>three</div>
</div>

<script>
    $(function(){
        $('#foo div').on('click', function(){
            $(this).siblings('div').removeClass('clicked');
            $(this).addClass('clicked');
        });
    });
</script>
4

3 回答 3

26

使用指令,因为您想遍历 DOM:

app.directive('sibs', function() {
    return {
        link: function(scope, element, attrs) {
            element.bind('click', function() {
                element.parent().children().removeClass('clicked');
                element.addClass('clicked');
            })
        },
    }
});

<div sibs>One</div>
<div sibs>Two</div>
<div sibs>Three</div>

请注意,jQuery 不是必需的。

fiddle

于 2013-08-13T15:00:26.950 回答
9

这是您提供的 jQuery 示例的 Angular 版本:

HTML:

<div ng-controller="FooCtrl">
    <div ng-click="selected.item='One'" 
    ng-class="{clicked:selected.item=='One'}">One</div>
    <div ng-click="selected.item='Two'" 
    ng-class="{clicked:selected.item=='Two'}">Two</div>
    <div ng-click="selected.item='Three'" 
    ng-class="{clicked:selected.item=='Three'}">Three</div>
</div>

JS:

function FooCtrl($scope, $rootScope) {   
    $scope.selected = {
        item:""
    }
}

注意:您不需要为此访问 DOM。但是,如果您仍然想要,那么您可以编写一个简单的指令。如下所示:

HTML:

<div ng-controller="FooCtrl">
    <div ng-click="clicked()" get-siblings>One</div>
    <div ng-click="clicked()" get-siblings>Two</div>
    <div ng-click="clicked()" get-siblings>Three</div>
</div>

JS:

yourApp.directive('getSiblings', function() {
   return {
      scope: true,
      link: function(scope,element,attrs){
         scope.clicked = function () {
            element.siblings('div').removeClass('clicked');
            element.addClass('clicked');
         }
      }
   }
});

fiddle

于 2013-08-13T14:48:07.933 回答
1

以下是专门使用 Angular 语法构建的指令(借用自 jqLit​​e):

link: function(scope, iElement, iAttributes, controllers) {
    var parentChildren,
        mySiblings = [];

    // add a marker to this element to distinguish it from its siblings
    // this could be a lot more robust
    iElement.attr('rsFindMySiblings', 'anchor');

    // get my parent's children, it will include me!
    parentChildren = iElement.parent().children();

    // remove myself
    scope.siblings = [];
    for (var i=0; i < parentChildren.length; i++) {
       var child = angular.element(parentChildren[i]);
       var attr = child.attr('rsFindMySiblings');
       if (!attr) {
         scope.siblings.push({name: child[0].textContent});  
       }
    }
}

请注意,它使用控制器来存储结果。有关详细示例,请参阅此plunker

于 2016-04-23T01:12:36.980 回答