获取当前元素

iLe*_*ing 7 angularjs

可以ng-click通过使用$event属性拦截类似处理程序中的当前事件对象.

但是有可能获得调用该方法的元素吗?

例如:

<div ng-controller='myController'>
  <div>{{distortThatDiv($element)}}</div>
</div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ley 6

如果你要操纵DOM,你真的应该使用一个指令.但是,如果您有$event,则可以轻松触发事件触发的原始​​元素:

$scope.clickHandler = function($event) {
   var element = $event.target;
};
Run Code Online (Sandbox Code Playgroud)


asg*_*oth 4

使用 Angular 指令可以轻松访问该元素。只需使用链接功能:

angular.module('myModule', [], function ($compileProvider) {
    $compileProvider.directive('distortThatDiv', function distortThatDivDirective() {
        return {
            restrict: 'A',
            link : function (scope, element, attrs) {
               element.on('click', function () {
                 // do something
               });
            } 
        };
    });
});
Run Code Online (Sandbox Code Playgroud)

你的 html 是:

<div ng-controller='myController'>
  <a distort-that-div>My link</a>
</div>
Run Code Online (Sandbox Code Playgroud)