监控在AngularJS指令元素阶级变化 [英] Monitor for class changing on element in AngularJS directive

查看:128
本文介绍了监控在AngularJS指令元素阶级变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个类被添加到一个元素,我想另一个类添加到该元素。当一个类被删除,我想删除的元素。我基本上映射了一些自举类在一定的角度表单验证类,但我无法弄清楚如何解雇我的code当一个类被添加/删除从元素(也确保不造成某些无限循环类变化)。

When a class is added to an element, I want to add another class to that element. When a class is removed, I want to remove an element. I'm basically mapping some bootstrap classes to some angular form validation classes but I can't figure out how to fire my code when a class is added/removed from an element (also making sure not to cause some infinite loop of class changing).

下面是我到目前为止我指令:

Here is what I have thus far for my directive:

.directive('mirrorValidationStates', ['$log', function($log) {
  function link(scope,element,attrs) {
    scope.$watch(element.hasClass('someClass'), function(val) {
      var classMap = {
        'popupOn': 'has-error',
        'ng-valid': 'has-success'
      };

      for (var key in classMap) {
        if (element.hasClass(key)) {
          $log.info("setting class " + classMap[key]);
          element.parent().addClass(classMap[key]);
        } else {
          $log.info("removing class " + classMap[key]);
          element.parent().removeClass(classMap[key]);
        }
      }
    });
  }
  return {
    link: link
  };
}]);

所以基本上,当 popupOn 添加到一个元素,我想补充的有误差引导类到父元素。当 popupOn 被删除,我想删除有误差

So basically, when popupOn is added to an element, I want to add the has-error bootstrap class to the parent element. When popupOn is removed, I want to remove has-error.

我想什么来做到这一点的角?也许一些与纳克级的,而不是用一个指令?

What am I missing to make this happen in Angular? Maybe something with ng-class and not use a directive?

谢谢了!

推荐答案

这里工作

works here

您可能会想尝试这种结构遵循类的变化:

You may want to try this construction to follow class changes:

scope.$watch(function() {return element.attr('class'); }, function(newValue){});

请注意添加/删除类的见解,看会导致增加这不会改变class属性值类的一个额外的电话。

Please notice that adding/removing classes insight that watch will cause one additional call of adding class that wont change class attribute value.

但我认为,更好的方法将使用纳克级。例如,在一个时刻,你想添加一个popupOn类要设置一定的范围值($ scope.popup = TRUE),然后指定NG-类父和子元素,像这样:

But I think the better approach will be using ng-class. For example in a moment you want to add a 'popupOn' class you are setting some scope value ($scope.popup = true) and then specify ng-class for parent and child element like so:

<div ng-class={'has-error': (popup==true)}>
    <div id="patient" ng-class={'popupOn': (popup==true)}>test</div>
    <button ng-click="addClass()">addClass</button>
    <button ng-click="removeClass()">removeClass</button>
</div>

当要删除这些类你刚才设置$ scope.popup值设置为false

when you want to remove those classes you just set $scope.popup value to false

拨弄纳克级

这篇关于监控在AngularJS指令元素阶级变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆