0

I'm trying to get the attribute value of element but return undefined.

html

<button id="myId" ng-click="hi($event)">click me</button>

js

$scope.hi = function (e) {
   var elem = angular.element(e.srcElement);
   alert(elem.attr("id"));

}

why i get undefined?

2 Answers 2

1

Change e.srcElement to e.target

example:

 $scope.hi = function (e) {

    var elem = angular.element(e.target);
      alert(elem.attr("id"));
}

DEMO

OR u can use

$scope.hi = function (e) {
     alert(e.target.id);
}

DEMO

Sign up to request clarification or add additional context in comments.

Comments

0

$event will pass the click event to your function.

For working with the element itself, you should use a directive.

 app.directive('mydirectiver', function() {
return {

    link: function(scope,element,attrs){

        //element will point to the element

        //attrs will point to the elements attributes

    }

};
});

I strongly recommend the lecture of the Angular docs on directives. They are a little confusing in the beginning, but you should be able to wrap your head around the concept very fast and benefit from their power.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.