Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have block of AngularJS code that looks like the following:

<ion-list can-swipe="true">
  <ion-item ng-repeat="item in items" simplify-item>
    <div class="row" style="background-color:orange;">
      Hello
    </div>
  </ion-item>
</ion-list>

The directives come from the ionic framework. Still, I am trying to add my own directive to this. I want to set a CSS property via an attribute called "simplify-item". My directive to make this happen looks like this:

myApp.directive('simplifyItem', function() {
  return {
    restrict:'A',
    link: function(element) {
      console.log('linking element');
      if (element === null) {
        console.log('element is null');
      } else {
    var result = element.hasClass('item-complex');
    if (result === null) {
      console.log('result is null.');
    } else {
      console.log('Sweet!');
    }
      }
    }
  };
});

When the line var result = element.hasClass('item-complex'); gets executed, I get an exception. The exception says:

undefined is not a function

I don't understand why I can't do this. What am I doing wrong?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

try like this

myApp.directive('simplifyItem', function() {
  return {
    restrict:'A',
    link: function(scope , iElement, iAttrs) {
     var element = iElement;
      console.log('linking element');
      if (element === null) {
        console.log('element is null');
      } else {
    var result = element.hasClass('item-complex');
    if (result === null) {
      console.log('result is null.');
    } else {
      console.log('Sweet!');
    }
      }
    }
  };
});

explanation from angular docs

Directives that want to modify the DOM typically use the link option. link takes a function with the following signature, function link(scope, element, attrs) { ... } where:

  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is a hash object with key-value pairs of normalized attribute names and their corresponding attribute values.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.