2

When I run this plunker I press the arrow-down of the dropdown and I assume that the dropdown list pop ups now but it does not

In my browser console I have no error.

Why can the dropdown not be clicked?

http://plnkr.co/edit/WHswYfce44W6WWZR1T7y?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  var schoolclassCodeColors = [
    {background:'blue'},

    {background:'red'}
    ];

  var newSubject = "test";
  var newSchoolclass = "11";
  var newSchoolclassIdentifier = "xb";

    $scope.activeStep = {};
  $scope.activeStep.schoolclassCodeColors = schoolclassCodeColors;
  $scope.activeStep.schoolclassCodeColorsIsOpen = false;

  $scope.activeStep.selectedSchoolclassCodeColor = $scope.activeStep.schoolclassCodeColors[0];

  $scope.activeStep.schoolclassCode = function () {
       return newSubject + newSchoolclass + newSchoolclassIdentifier;
  };

  $scope.activeStep.setSchoolclassCodeColor = function(color){
    $scope.activeStep.selectedSchoolclassCodeColor = color;
    this.schoolclassCodeColorsIsOpen = false;

 };
});

app
.constant('dropdownConfig', {
  openClass: 'open'
})

.service('dropdownService', ['$document', function($document) {
  var openScope = null;

  this.open = function( dropdownScope ) {
    if ( !openScope ) {
      $document.bind('click', closeDropdown);
      $document.bind('keydown', escapeKeyBind);
    }

    if ( openScope && openScope !== dropdownScope ) {
        openScope.isOpen = false;
    }

    openScope = dropdownScope;
  };

  this.close = function( dropdownScope ) {
    if ( openScope === dropdownScope ) {
      openScope = null;
      $document.unbind('click', closeDropdown);
      $document.unbind('keydown', escapeKeyBind);
    }
  };

  var closeDropdown = function( evt ) {
    // This method may still be called during the same mouse event that
    // unbound this event handler. So check openScope before proceeding.
    if (!openScope) { return; }

    var toggleElement = openScope.getToggleElement();
    if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {
        return;
    }

    openScope.$apply(function() {
      openScope.isOpen = false;
    });
  };

  var escapeKeyBind = function( evt ) {
    if ( evt.which === 27 ) {
      openScope.focusToggleElement();
      closeDropdown();
    }
  };
}])

.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {
  var self = this,
      scope = $scope.$new(), // create a child scope so we are not polluting original one
      openClass = dropdownConfig.openClass,
      getIsOpen,
      setIsOpen = angular.noop,
      toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;

  this.init = function( element ) {
    self.$element = element;

    if ( $attrs.isOpen ) {
      getIsOpen = $parse($attrs.isOpen);
      setIsOpen = getIsOpen.assign;

      $scope.$watch(getIsOpen, function(value) {
        scope.isOpen = !!value;
      });
    }
  };

  this.toggle = function( open ) {
    return scope.isOpen = arguments.length ? !!open : !scope.isOpen;
  };

  // Allow other directives to watch status
  this.isOpen = function() {
    return scope.isOpen;
  };

  scope.getToggleElement = function() {
    return self.toggleElement;
  };

  scope.focusToggleElement = function() {
    if ( self.toggleElement ) {
      self.toggleElement[0].focus();
    }
  };

  scope.$watch('isOpen', function( isOpen, wasOpen ) {
    $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);

    if ( isOpen ) {
      scope.focusToggleElement();
      dropdownService.open( scope );
    } else {
      dropdownService.close( scope );
    }

    setIsOpen($scope, isOpen);
    if (angular.isDefined(isOpen) && isOpen !== wasOpen) {
      toggleInvoker($scope, { open: !!isOpen });
    }
  });

  $scope.$on('$locationChangeSuccess', function() {
    scope.isOpen = false;
  });

  $scope.$on('$destroy', function() {
    scope.$destroy();
  });
}])

.directive('dropdown', function() {
  return {
    controller: 'DropdownController',
    link: function(scope, element, attrs, dropdownCtrl) {
      dropdownCtrl.init( element );
    }
  };
})

.directive('dropdownToggle', function() {
  return {
    require: '?^dropdown',
    link: function(scope, element, attrs, dropdownCtrl) {
      if ( !dropdownCtrl ) {
        return;
      }

      dropdownCtrl.toggleElement = element;

      var toggleDropdown = function(event) {
        event.preventDefault();

        if ( !element.hasClass('disabled') && !attrs.disabled ) {
          scope.$apply(function() {
            dropdownCtrl.toggle();
          });
        }
      };

      element.bind('click', toggleDropdown);

      // WAI-ARIA
      element.attr({ 'aria-haspopup': true, 'aria-expanded': false });
      scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {
        element.attr('aria-expanded', !!isOpen);
      });

      scope.$on('$destroy', function() {
        element.unbind('click', toggleDropdown);
      });
    }
  };
});

HTML

  </head>

  <body ng-controller="MainCtrl">
    <div class="col-md-6">
      <div class="btn-group" dropdown is-open="activeStep.schoolclassCodeColorsIsOpen">
          <button type="button" ng-style="{{activeStep.selectedSchoolclassCodeColor}}"
                  class="btn btn-primary dropdown-toggle" ng-disabled="disabled">
              {{activeStep.schoolclassCode()}} <span class="caret"></span>
          </button>
          <ul class="dropdown-menu" role="menu">
              <li ng-repeat="color in activeStep.schoolclassCodeColors">
                  <a ng-style="{{color}}"
                     ng-click="activeStep.setSchoolclassCodeColor(color)">{{activeStep.schoolclassCode()}}</a>
              </li>
          </ul>
      </div>
  </div>
  </body>

</html>
HelloWorld
  • 4,671
  • 12
  • 46
  • 78

3 Answers3

1

In order to use the dropdownToggle directive inside the class attribute, you need to define the restrict permissions from the directive to include the C (Class). For example:

.directive('dropdownToggle', function() {
  return {
    restrict: 'AEC',
    require: '?^dropdown',
    // ...
});

From Angular's documentation:

The restrict option is typically set to:

'A' - only matches attribute name

'E' - only matches element name

'C' - only matches class name

Demo

bmleite
  • 26,850
  • 4
  • 71
  • 46
  • Why has the original source: https://github.com/angular-ui/bootstrap/blob/master/src/dropdown/dropdown.js NOT the AEC restrict set/used ??? – HelloWorld Oct 14 '14 at 13:44
  • Probably because they don't want us to use it in the `class` attribute (normally `class` is for styles and not for "functionalities"). The default value is `'EA'` (**E**lements and **A**ttributes), so you should be able to use the directive in both those modes. – bmleite Oct 14 '14 at 13:55
  • Ok the problem was I used the directive not as the author want it! I have now put the directive on an a-tag then it works without AEC restriction! But there is a visual bug, now the directive is on the a-tag the round corners on the right side are gone! – HelloWorld Oct 14 '14 at 14:02
0
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />

<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script>
<script src="app.js"></script>

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

you need to add bootstrap.min.js and jquery.js javascript files, and also you need to add, data-toggle="dropdown" attribute to button as below

 <button type="button" ng-style="{{activeStep.selectedSchoolclassCodeColor}}"
              class="btn btn-primary dropdown-toggle" ng-disabled="disabled" data-toggle="dropdown">    

here is the plunker demo

Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
0

That seems like an awful lot of code for what you are trying to do. I can't tell if the answer below is what you are looking for. I'm assuming you are trying to create an angular-only version of the bootstrap toggle.

It seems like you have misunderstood the way that require and the controller attribute of the directive work. I think that the angular docs are probably the source of this confusion unfortunately:

When a directive requires a controller, it receives that controller as the fourth argument of its link function.

It says that the directive requires a controller, but it is actually the case that the directive requires another directive. And that required directive's controller is passed to the linking function.

The controller attribute should not be a string (controller: 'DropdownController',), but should be a constructor function for the controller. So I think you can solve your issue by moving your DropdownController into the directive.

For an example of something similar (but simpler) you can see this answer and the plnkr.

Community
  • 1
  • 1
trey-jones
  • 3,329
  • 1
  • 27
  • 35