如何编写通过选择器切换类的angular指令

时间:2016-10-06 20:51:10

标签: javascript angularjs angularjs-directive

我试图编写一个基于选择器条件切换类的指令:

<label class-when="{'is-checked': ':has(input:checked)', 'is-disabled': ':has(input:disabled)'}">
    <input type="checkbox">
    Example checkbox
</label>

我需要以某种方式监视元素及其后代的DOM更改,但我得到ng:areq error。我怎么能这样做?

define(function (require) {
    var _ = require('lodash');

    return {
        restrict: 'A',
        scope: {
            object: '@classWhen'
        },
        link: function (scope, element) {
            scope.$watchCollection(function() {
                return element.find('*').add(element);
            }, function () {
                _.forOwn(scope.object, function (test, classes) {
                    test = typeof test === 'boolean' ? test : element.is(test);
                    element.toggleClass(classes, test);
                });
            });
        }
    };
});

3 个答案:

答案 0 :(得分:6)

好的,在阅读了您的赏金评论之后,我明白您希望这是独立于控制器的。我花了一些时间完全重新设计我的解决方案,我想我终于想出了一种方法来实现你想要的。

这真的归结为两件事:

1)检查复选框:checked状态和

的更改

2)检查复选框:disabled状态

上的更改

检测1)很简单,因为您可以使用简单的jQuery更改处理程序,但检测2)需要更多的研究。它需要在子scope.$watch属性上使用ng-disabled

这是一个如何工作的演示:

&#13;
&#13;
var app = angular.module("myApp", [])
  .directive("classWhen", function() {
    function setClasses(classWhen, $element, $input) {
      Object.keys(classWhen).forEach(function(key) {
        var test = classWhen[key];
        // .toggleClass("className", true) === .addClass("className")
        // .toggleClass("className", false) === .removeClass("className")
        $element.toggleClass(key, $element.is(test));
      });
    }
    return {
      restrict: 'A',
      link: function link (scope, element, attrs) {
        var classWhen = JSON.parse(attrs.classWhen);
        var $element = $(element);
        $element.find("*").each(function (index, elem) {
          var $elem = $(this);
          // namespace the change event so we can easily .off() it
          $elem.off("change.classWhen");
          $elem.on("change.classWhen", function () {
            setClasses(classWhen, $element, $elem);
          });
          // watch child ng-disabled attribute
          scope.$watch($elem.attr("ng-disabled"), function (val) {
            setClasses(classWhen, $element, $elem);
          });
        });
      }
    };
  });
&#13;
.is-checked {
  background-color: yellow;
}
.is-disabled {
  background-color: lightblue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myApp">
  <label>
    <input type="checkbox" ng-model="disableAll" />Disable All</label>
  <br>
  <br>
  <label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
    <input type="checkbox" ng-disabled="disableAll">Example checkbox 1
  </label>
  <br>
  <label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
    <input type="checkbox" ng-disabled="disableAll">Example checkbox 2
  </label>
  <br>
  <label class-when='{"is-checked": ":has(input:checked, .test)", "is-disabled": ":has(input:disabled)"}'>
    <input type="text" ng-disabled="disableAll" ng-class="testingClass" ng-model="testingClass"/>
    <br>
    <input type="checkbox" ng-disabled="disableAll">
    Example checkbox 3
  </label>
  <br>
  <label class-when='{"is-checked": ":has(input:checked)", "is-disabled": ":has(input:disabled)"}'>
    <input type="checkbox" ng-disabled="disableAll">Example checkbox 4
  </label>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

以下是我尝试以通用方式解决您的问题:https://plnkr.co/edit/kVyJQClmQhF3FeBTmKaX?p=preview

指令代码:

app.directive('classWhen', () => (scope, element, attrs) => {
  scope.$watchCollection(getClasses, setClasses)

  function getClasses() {
    // We have to evaluate expression in attrs.classWhen so that we get object
    const rawClasses = scope.$eval(attrs.classWhen)
    const classes = {}

    // then we normalize it so that strings are treated as jquery selectors
    Object.keys(rawClasses).forEach((className) => {
      const expr = rawClasses[className]
      classes[className] = typeof expr === 'string'
        ? element.is(expr)
        : !!expr // we normalize falsy values to booleans
    })

    // then we return it to $watchCollection
    return classes
  }

  /**
   * will be called whenever any of the classes changes
   */
  function setClasses(classes) {
    Object.keys(classes).forEach((className) => {
      element.toggleClass(className, classes[className])
    })
  }
})

答案 2 :(得分:0)

我为此创建了一个通用的小提琴,并且使用了RequireJS。

请看这里

http://fiddle.jshell.net/balasuar/dugmu/15/

注意:无论您在curl_setopt($ch, CURLOPT_USERNAME, base64_encode("{$username}:"));:checked等选择器中添加了什么属性,都要将相关的angular属性添加到子元素,如:disabledng-model。它会像魅力一样工作!!

<强>代码

&#13;
&#13;
ng-disabled
&#13;
var app = window.app = angular.module("myApp", []);

define('classWhenDirective', function () {
    //var _ = require('lodash');
    var app = window.app;debugger;
    app.directive("classWhen", function() {
    return {
    restrict: 'A',
    link: function(scope, element, attrs) {
          scope.$watch(getChanges, setClasses)

  function getChanges() {
    var attrs = [];
    
    function getAttrs(elm) {
       $.each(elm.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
       if(value && name.indexOf('ng-') > -1) {
         value = scope.$eval(value);
       }
     if(value) {      
       attrs.push(name + ':' + value);
     }
  });
     
    }
    
    getAttrs(element.get(0));
    
    element.children().each(function(){
       getAttrs(this);
    });
    
    return attrs.join(',');
  }

  function setClasses() {
    var rawClasses = scope.$eval(attrs.classWhen);

    Object.keys(rawClasses).forEach(function(className){
      var expr = rawClasses[className]
      var setClass = typeof expr === 'string'
        ? element.is(expr)
        : !!expr;
       element.toggleClass(className, setClass);
    });
  }
    }
  };   
    });
});

define('todo', ['classWhenDirective'], function() {
  var app = window.app;
  app.controller('myController', function($scope) {

  });
});

// angular bootstrap
require(['todo'], function() {
  angular.bootstrap(document, ['myApp']);
});
&#13;
.is-checked {
  color: green;
}
.is-disabled {
  color: gray;
}
&#13;
&#13;
&#13;