4

How can I grab an element's attr data in angular with jqlite?

html,

<button ng-click="loadForm($event)" href="form.php">Load Directive Form</button>
<div data-my-form></div>

angular,

     app.directive('myForm', function() {
        return {
          controller:function($scope){
            $scope.isLoaded = false;
            $scope.loadForm = function(e){

                console.log(e.target.attr('href')); // error 

                var form = e.target.attr('href'); // error

                $scope.isLoaded = true;
            }
          },
          template: '<div><div ng-if="isLoaded" ng-include="'+ form +'" ></div></div>',
          link:function(scope, element) {

          }
        }
    });

I get this error,

TypeError: e.target.attr is not a function

any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748
  • Use `e.target.href` or `e.target.getAttribute('href')`, depending on whether or not you want the absolute or relative link. Still I wonder why do you assign _href_ attribute to a non-link element. – raina77ow Dec 13 '14 at 09:10
  • i get this error `Error: [$parse:syntax] Syntax Error: Token 'HTMLDivElement' is unexpected, expecting []] at column 9 of the expression [[object HTMLDivElement]] starting at [HTMLDivElement]].` – Run Dec 13 '14 at 09:13
  • 1
    `form` variable is defined as local to controller function, yet you attempt to use it in the template. – raina77ow Dec 13 '14 at 09:16
  • Aww I see. I get null anyway with `e.target.href;`. – Run Dec 13 '14 at 09:22

1 Answers1

6

attr() is method available on jqLite elements.

e.target is a reference to a DOM element.

You need to wrap the DOM element as a jqLite element first:

var form = angular.element(e.target).attr('href');
tasseKATT
  • 38,470
  • 8
  • 84
  • 65