2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

angularでbemを楽に書きたい

Posted at

作った(demo)。

モチベーション

bemとか書くの面倒すぎだろうが。

使い方

これが

<div bem="block--foo,bar">
  <div bem="__element--mod">
    <div bem="__a--mo">a</div>
    <div bem="__b">b</div>
  </div>
</div>

こうなる。

<div bem="block--foo,bar" class="block block--foo block--bar">
  <div bem="__element--mod" class="block__element block__element--mod">
    <div bem="__a--mo" class="block__element__a block__element__a--mo">a</div>
    <div bem="__b" class="block__element__b">b</div>
  </div>
</div>

実装

app.directive('bem', () => {
  function Ctrl($element, $attrs) {
    var match = $attrs.bem.trim().match(/^(.*?)(?:--(.*))?$/);
    if (!match) throw new Error('bem: invalid pattern');
    var modifiers = match[2] ? match[2].split(',') : [];
    this.be = /^__/.test(match[1]) ?
      $element.parent().controller('bem').be + match[1] : match[1];
    $element.addClass([this.be].concat(modifiers.map(m => `${this.be}--${m}`)).join(' '));
  }
  
  return {
    restrict: 'A',
    controller: Ctrl
  };
});

参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?