Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass element to Angular directive

I have a simple popup directive similar to https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js

I need to position my popup close to element that initiated the open.

What is best way to make this? Would capturing the initiator with ng-click="open($event)" and passing to directive work? (here is sample of this element capturing http://jsfiddle.net/Amnesiac/5z5Qz/3/ )

$scope.open= function (e) {
   var elem = angular.element(e.srcElement);
}

How do I then pass this angular.element(e.srcElement) to directive ? (directive would then do some calculations based on position of that passed dom element and re-position the popup)

like image 460
dzolnjan Avatar asked Aug 06 '13 22:08

dzolnjan


People also ask

How do you pass data into a directive?

If you want to send data to directive then you should try like this: This is my custom directive, and I am going to share two value from component or HTML to the directive. You will have to use your directive in your html and send data to the directive like in below code. I am sending name and value to the test.

What is ElementRef in Angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

How do I create a custom directive?

To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color. Create an app-highlight.


1 Answers

Pass it like you would any other scope property, e.g., modal el="clickedElement":

<button id="myId" ng-class="{'blueBg': blueBg}" ng-click="hi($event)">click me</button> 
<div modal el="clickedElement"></div>

angular.module('Test',[])
.controller('Foo', function ($scope, $element) {
    $scope.blueBg = false;
    $scope.hi = function (ev) {
       $scope.blueBg = true;
       $scope.clickedElement = angular.element(ev.srcElement);
    }
})
.directive('modal', function() {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.el, function(value) {
                if(value !== undefined) {
                    console.log('element=',value);
...

fiddle

like image 59
Mark Rajcok Avatar answered Oct 04 '22 05:10

Mark Rajcok