javascript 将元素传递给 Angular 指令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18091672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass element to Angular directive
提问by dzolnjan
I have a simple popup directive similar to https://github.com/angular-ui/bootstrap/blob/master/src/modal/modal.js
我有一个类似于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/)
什么是最好的方法?会用 ng-click="open($event)" 捕获发起者并传递给指令吗?(这里是这个元素的示例捕获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)
然后我如何将这个 angular.element(e.srcElement) 传递给指令?(然后指令将根据传递的 dom 元素的位置进行一些计算并重新定位弹出窗口)
回答by Mark Rajcok
Pass it like you would any other scope property, e.g., modal el="clickedElement"
:
像传递任何其他范围属性一样传递它,例如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);
...