简体   繁体   中英

Get DOM element attribute of parent container with AngularJS

I'am quite new to AngularJS and I try to achieve to following: on click on some outer element and also on click on it's child elements I want to get some attribute of the outer element.

In jQuery this seems to bubble up easily when i click the subelement. In Angular, the function I put on "ng-click" on the outer element gets called, but the attribute can't be fetched... I put my example with Angular and jQuery here: http://www.allcontrasts.com/external/angular-jquery/index.html

The critial code is the following:

HTML:

<body ng-app="testApp" ng-controller="testController" >
  <div class="angulardiv" ng-click="myAlert($event);" data-id="321">ANGULAR
    <div class="sublement">
        Subelement
    </div>
  </div>
  <div class="jquerydiv" data-id="321">JQUERY
    <div class="sublement">
        Subelement
    </div>
  </div>
</body>

Angular-Code:

var app = angular.module('testApp', []);
app.controller('testController', function($scope) {
    $scope.myAlert = function(event) {
        var elem = angular.element(event.target);
        var dataId = elem.attr('data-id');
        alert(dataId);
    }
});

jQuery:

$(document).ready(function() {
    $('.jquerydiv').click(function() {
        alert($(this).attr('data-id'));
    })
});

How can I achieve with Angular what jQuery does in this case?

Ok, in this case the soultion was pretty easy, I could change my HTML to:

<div class="angulardiv" ng-click="myAlert(321);">ANGULAR
  <div class="sublement">
     Subelement
  </div>
</div>

...just passing the needed ID directly as a parameter to the function.

And then changed the Angular Code to:

var app = angular.module('testApp', []);
app.controller('testController', function($scope) {
    $scope.myAlert = function(obj) {
        alert(obj);
    }
});

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