最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get current dom element in angular directive - Stack Overflow

programmeradmin3浏览0评论

I am new to angularjs, just like many other developer, I was jquery developer. Now I have a question about directive. example: if i have a directive like this:

app.directive('mydiv',function(){
     return{
     restrict:'AE',
     template:'<div><ul><li></li><li></li><li></li></ul></div>', //of course in real case it will be use ng-repeat
     link:function(scope,element,attr){

     }
}               
})

the confuse I have is,if I need to access any

  • element,in jquery we can use $(this), how can we do it with angular way? Can I do like this:

    link: function (scope, element, attrs) {    //when hover show the delete icon for each msg and apply highlight class to it.
                    element.find('li').hover(
                            function(){
                                $(this).addClass('highlight');
                                scope.deleteicon=true;
                            },
                            function(){
                                $(this).removeClass('highlight');
                                scope.deleteicon=false;
                            });                 
            }
    

    I am new to angularjs, just like many other developer, I was jquery developer. Now I have a question about directive. example: if i have a directive like this:

    app.directive('mydiv',function(){
         return{
         restrict:'AE',
         template:'<div><ul><li></li><li></li><li></li></ul></div>', //of course in real case it will be use ng-repeat
         link:function(scope,element,attr){
    
         }
    }               
    })
    

    the confuse I have is,if I need to access any

  • element,in jquery we can use $(this), how can we do it with angular way? Can I do like this:

    link: function (scope, element, attrs) {    //when hover show the delete icon for each msg and apply highlight class to it.
                    element.find('li').hover(
                            function(){
                                $(this).addClass('highlight');
                                scope.deleteicon=true;
                            },
                            function(){
                                $(this).removeClass('highlight');
                                scope.deleteicon=false;
                            });                 
            }
    
    Share Improve this question edited Jan 7, 2015 at 23:24 PSL 124k21 gold badges256 silver badges243 bronze badges asked Jan 7, 2015 at 22:56 linyuanxielinyuanxie 7874 gold badges13 silver badges31 bronze badges 1
    • 1 In your link function you have the parameter injected called "element" which will be a jqLite element. – Himmet Avsar Commented Jan 7, 2015 at 22:58
    Add a ment  | 

    3 Answers 3

    Reset to default 3

    You can access the element as the 1st argument (element argument in your case) of the link function itself. If you are using jquery with angular and loading jquery before angular the element` will be wrapped in jquery wrapper, i.e it will be a jquery object. If not angular uses a lighter subset of jquery called jqlite. It only provided a minimal functionality.

    See element for details.

    Instead of binding hover event manually you should use angular event binding and use ng-class instead of add/remove class. That way you perform things angular way and you do not need to manually invoke digest cycle via scope.$apply() for DOM updates with respect to scope updates (Which you need to do in the hover pseudo event in your example to reflect DOM updates based on scope property deleteicon).

    An example implementation of your directive will look like this. There are numerous ways you can do this using angular built-in directives itself.

    .directive('mydiv',function(){
         return {
         restrict:'AE',
         scope:{items:"="}, //<-- data bound from parent scope via attribute
         template:'<div><ul><li ng-mouseenter="toggleClass(true)" ng-mouseleave="toggleClass(false)" ng-class="{'highlight': action.deleteicon}" ng-repeat="item in items">{{item.name}}</li></ul></div>', //of course in real case it will be use ng-repeat
         link:function(scope,element,attr){
            scope.action = {deleteicon :true};
            scope.toggleClass = function(show){
                 scope.action.deleteicon = show;
            }
         }
       }               
    });
    
    • scope:{items:"="}, sets up 2 way binding if you wish to bind the data from the parent scope via attribute.

    • Instead of repeating li use a data model, say an array of items and use ng-repeat instead of duplicating the tag (unless you need to do it for sure). ex:- ng-repeat="item in items"

    • Use angular event bindings instead of binding the events manually, hover is nothing but nouseenter/mouseleave. So you can use respective angular directives and bind a function on the scope. i.e ng-mouseenter="toggleClass(true)" ng-mouseleave="toggleClass(false)".

    • Use ng-class bound to a scope variable to toggle the class. Let angular manage DOM manipulation for toggling the css class on the element. You just worry about the data being bound. i.e ng-class="{'highlight': action.deleteicon}"

    You can find official documentation on angular built in directives/ponents.

    Well, you used hover, but, you can use the MouseOver Directive.

    As the following example:

    <li ng-mouseover="high = true" ng-class="{'highlight':high}">Content</li>
    

    Look at this plkr

    Markup:

    <div class="row" ng-app="myapp" ng-controller="myctrl">
            <div class="col-lg-3 col-lg-push-3">
                <ul class="list-group">
                    <li class="list-group-item" ng-init="myclass='hide'" ng-repeat="item in items"
                        ng-mouseenter="myclass = 'show'" ng-mouseleave="myclass='hide'">
                        <span>{{item}}</span>
                        <span ng-class="'pull-right glyphicon glyphicon-edit '+myclass"></span>
                    </li>
                </ul>
            </div>
        </div>
    

    Script:

    angular.module('myapp', [])
                .controller('myctrl', function ($scope) {
                    $scope.items = ['abc', 'xyz', 'klm'];
                });
    
  • 发布评论

    评论列表(0)

    1. 暂无评论