使用带有ng-class

时间:2016-02-16 20:04:49

标签: angularjs angularjs-directive angularjs-ng-class

我在ng-class模板中引用控制器中变量的值,但它不起作用。

这是html指令模板URl:

<div class="tooltip-anchor">
<div class=" tooltip-content ehub-body" ng-class="{ 'tooltip__content--disabled': tooltipContentValue}" ng-transclude>Tooltip content</div>
</div>

这是我在索引页面中使用该指令的地方

 <div style="text-align:center;">
  <a href="" ng-keyup="keyupevt()"><ehub-tooltip>Hello i am here, and i am her to stay</ehub-tooltip>over here</a>
  <a href="" ng-keyup="keyupevt()"><ehub-tooltip>Be nice to people on your way up and they will be nice to you on your way down</ehub-tooltip>click me</a>
 </div>

这是指令: 在这个指令中,我创建了一个变量并将其设置为false,并尝试在ng-class属性中使用它

(function(window){     'use strict';

angular
  .module('ehub.component.tooltip', [])
    .controller('ehubTooltipCtrl', ['$scope', function ($scope) {
        $scope.tooltipContentValue = false;

    }])
  .directive('ehubTooltip', ehubTooltip);

function ehubTooltip() {
    var directive = {
        controller: "ehubTooltipCtrl",
        link: link,
        transclude: true,
        templateUrl: 'ehub-tooltip.html',
        restrict: 'E'

    };
    return directive;

    function link(scope, element, attrs) {

        scope.keyupevt = function () {
            if (event.keyCode === 27) {
                $scope.tooltipContentValue = true;

            }
         }

     }
  }

})();

1 个答案:

答案 0 :(得分:0)

尝试这项工作jsfiddle

angular.module('ExampleApp', ['ngMessages'])
  .controller('ExampleController', function($scope) {

  })
  .directive('ehubTooltip', function() {
    var directive = {
      link: link,
      transclude: true,
      template: '<div class="tooltip-anchor"><div class=" tooltip-content ehub-body" ng-class="{ \'tooltip__content--disabled\': tooltipContentValue}" ng-transclude>Tooltip content</div></div>',
      restrict: 'E'
    };
     function link(scope, element, attrs) {
      scope.tooltipContentValue = false;
      scope.keyupevt = function() {
        if (event.keyCode === 27) {
          scope.tooltipContentValue = true;
        }
      }

    }
    return directive;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">

    <div style="text-align:center;">
      <a href="" ng-keyup="keyupevt()">
        <ehub-tooltip>Hello i am here, and i am her to stay</ehub-tooltip>over here</a>
      <a href="" ng-keyup="keyupevt()">
        <ehub-tooltip>Be nice to people on your way up and they will be nice to you on your way down</ehub-tooltip>click me</a>
    </div>
  </div>
</div>