Search code examples
javascriptangularjsangular-uiangular-ui-bootstrappopover

AngularUI popover style change of parent element on click


I have a pretty specific problem. Recently I figured out how to add a close button to an AngularUI popover. Originally the user had to click on the popover parent to open and to close it, so I had functionality added in that changed the style of that element on a click event. With the addition of the close button, I want to simulate the same effect when the user clicks it. I set up a plnkr here to play with.

So far I've tried to add ng-click="toggle(); style=!style" in the popover template, but that didn't work. I think that I have to access the style variable in the popoverToggle directive, but I don't know how to do that. It might also just be possible to manipulate it in the HTML.

Popover template

<div><span ng-click="toggle()">X</span></div>
<p>content</p>

popoverToggle.js

angular.module('app')
    .config(function($tooltipProvider) {
        $tooltipProvider.setTriggers({'open': 'close'});
      })

      .directive('popoverToggle', function($timeout) {
        return {
          scope: true,
          link: function(scope, element, attrs) {
            scope.toggle = function() {
              $timeout(function() {
                element.triggerHandler(scope.openned ? 'close' : 'open');
                scope.openned = !scope.openned;
                scope.style = !scope.style; // doesn't do anything either
              });
            };
            return element.on('click', scope.toggle);
          }
        };
      });

index.html

<span ng-class="{'border-gray': style}" style="margin: 40px" ng-click="style=!style" class="red-btn">
  <span popover-placement="bottom" popover-template="'popover-template.html'"
  popover-trigger="open" popover-append-to-body="true" popover-toggle>click me</span>
</span>

Solution

  • The solution is very straightforward, all that needs to be changed is the style variable. Simply change it to $scope.style, like so:

    popover-template.html

    <div><span ng-click="toggle(); $scope.style=!$scope.style">X</span></div>
    <p>content</p>
    

    index.html

    <span ng-class="{'border-gray': $scope.style}" style="margin: 40px" ng-click="$scope.style=!$scope.style" class="red-btn">
      <span popover-placement="bottom" popover-template="'popover-template.html'"
      popover-trigger="open" popover-append-to-body="true" popover-toggle>click me</span>
    </span>