Ravi Mittal
Ravi Mittal

Reputation: 1261

Angular directive is not working when used with two HTML elements?

I am new to AngularJS. I have created one directive using AngularJS which is working fine for me, but when i used this same directive with another HTML element then its not working.

basecampModule.directive("slideElement", function () {
  function link($scope, element, attributes) {
    var expression = attributes.slideElement;

    if (!$scope.$eval(expression)) {
      element.hide();
    }

    $scope.$watch(expression, function (newValue, oldValue) {
      if (newValue === oldValue) {
        return;
      }

      if (newValue) {
        element.stop(true, true).slideDown("fast");
        $('html, body').animate({
          scrollTop: $(element).offset().top
        }, 1000);
      } else {
        element.stop(true, true).slideUp("fast");
      }
    });
  }

  return ({
    link: link,
    restrict: "A"
  });
});

HTML Part

<div class="row well" id="detailsBugs" slide-element="FilterBugsDetails.ShowPanel">
       //FIRST ELEMENT
</div>

<div class="row well" id="detailsTasks" slide-element="FilterTaskDetails.ShowPanel">
       //SECOND ELEMENT
</div>

its working with first element but not with second element.

Please let me know what is wrong is that part. ??

Upvotes: 0

Views: 577

Answers (2)

Derek Ekins
Derek Ekins

Reputation: 11391

When I first looked at this I couldn't quite work out what was going on. The watched would fire for once but not a second time for the second directive.

However, turns out the directive is actually watching two different properties (maybe this was obvious to others but I completely missed it). From the question it sounded like the poster wanted the directive to watch the same element.

Anyway it works fine in my plunker here

<button ng-click="FilterBugsDetails.ShowPanel = !FilterBugsDetails.ShowPanel;">Toggle Bugs</button>
<button ng-click="FilterTaskDetails.ShowPanel = !FilterTaskDetails.ShowPanel;">Toggle Tasks</button>
<button ng-click="FilterTaskDetails.ShowPanel = !FilterTaskDetails.ShowPanel; FilterBugsDetails.ShowPanel = !FilterBugsDetails.ShowPanel;">Toggle Tasks And Bugs</button>

Upvotes: 0

charlysisto
charlysisto

Reputation: 3700

A very wilde guess : you should isolate the scope of you directive. Since both instances of this directive are using the same $scope they're probably conflicting :

http://www.egghead.io/video/fYgdU7u2--g

Upvotes: 1

Related Questions