【问题标题】:Angular directive is not adding css class to another elementAngular 指令未将 css 类添加到另一个元素
【发布时间】:2016-08-27 17:29:27
【问题描述】:

您好,我正在尝试使用 angular 指令在单击按钮时更改另一个元素的 CSS,但是尽管 console.log 显示已添加该类,但在检查器中仍然没有该类。

模态指令

angular.module('App.shared.modal')
.directive('openModal', function (Config) {

  function link(scope, element, attrs) {
    element.bind('click', function() {
      var modal = angular.element(document.querySelector('#' + attrs.openModal)).css('display', 'block');
      setTimeout(function(){ modal.className += ' modal-in'}, 10);
    });
  }
  return {
    restrict: 'AEC',
    link: link
  };
});

视图被称为指令

<header class="">
  <div class="u-max-full-width">
    <div class="row homehubusa-header">
      <div class="one-third column">
        <img src="./imgs/homehubusa.png" alt="logo homehubusa" class="logo"/>
      </div>
      <div class="two-thirds column">
        <ul class="menu u-pull-right">
          <li>
            <a href="#">HomesUSA</a><span class="separator">&nbsp;</span>
          </li>
          <li>
            <a href="#">Support</a><span class="separator">&nbsp;</span>
          </li>
          <li>
            <a href="#">Contact Us</a>
          </li>
          <li class="callsign">
            <a href="#" class="button button-danger" open-modal="modalLogin">Sign in</a>
          </li>
        </ul>
      </div>
    </div>
  </div>
</header>

标头指令

  angular.module('App.shared.header')
    .directive('appHeader', function (Config) {

      function link(scope) {
        scope.navLinks = [
          {title: 'Home', href: 'home'},
          {title: 'Help', href: 'seed-help'}
        ];
      }
      return {
        templateUrl: Config.rootPath + 'shared/header/header-view.html',
        link: link,
        replace: true
      };
    });

应用结构

<body ng-app="App">  
  <app-header></app-header> /* This is the header directive, here is the button */
  <div class="ng-view"></div> /* Here is the modal */
  <app-footer></app-footer>
</body>

【问题讨论】:

    标签: javascript css angularjs


    【解决方案1】:

    您不需要使用timeout 来应用CSS。在此处查看简化示例:JSFiddle

    你最好使用addClass,因为angular.element支持它:

     link: function(scope, element, attrs) {
        element.bind('click', function() {
          var target = angular.element(document.querySelector('#test'));
          target.css('display', 'block');
          target.addClass('red');
        });
    

    对于display: block,我怀疑您的元素#modalLogin 不存在,因为在我的示例中,它正在工作:JSFiddle

    【讨论】:

    • 但是css显示块也应该可以工作,但不能工作
    【解决方案2】:

    您可以检查 $apply() 方法。因为您使用的是 setTimeout() 方法。 setTimeout() 是异步的,由 JS 引擎处理。不是 Angular 编译器,所以你需要以某种方式告诉 Angular 我的 Js 引擎已经改变了一些东西,因此尝试使用 apply()。我不知道这会奏效。我的一个代码我做了这件事。成功了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多