简体   繁体   中英

How do I get current scope dom-element in AngularJS controller?

I have a list of outerItems. Inside each outerItem, I have a list of innerItems. They are dynamically sorted.

When mouse cursor points at one of innerItems, I have to show the popup window right above that innerItem element.

Popup div is body's child, because I do not want to have a separate popup for each of innerItems.

The way as I see it — on ng-mouseover I call the function that sets left/top properties to my absolutely positioned popup. So for each of innerItems I'd like to call jQuery .offset() method that gives me left/top values from the top-left corner of page.

So how can I get jQuery object of current scope element? Or, if I've chosen the wrong way

In controller:

function innerItem($scope, $element){
    var jQueryInnerItem = $($element); 
}

The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element to do DOM operations. The method defined in the directive controller is accessible in the main controller.

Example, finding a child element:

var app = angular.module('myapp', []);
app.directive("testDir", function () {
    function link(scope, element) { 

    }
    return {
        restrict: "AE", 
        link: link, 
        controller:function($scope,$element){
            $scope.name2 = 'this is second name';
            var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
    }
    };
})

app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM