简体   繁体   English

在指令中编辑/添加ngClass

[英]Edit/Add ngClass in directive

I am trying to create a directive to refactor some classes manipulation. 我正在尝试创建一个指令来重构某些类的操作。

Please take a look at this fiddle . 请看一下这个小提琴

I want to add or edit the ng-class attribute from my track directive to avoid this dupplicated code (in the ng-classes): 我想从我的track指令中添加或编辑ng-class属性,以避免重复代码(在ng-classes中):

<table>
  <tr ng-repeat="track in tracks"
      ng-class="{
        'track-is-stopped': trackState === 'stop',
        'track-is-playing track-is-paused': trackState === 'pause',
        'track-is-playing': trackState === 'play',
        'track-is-playing track-is-buffering': trackState === 'buffering'
      }"
      track>
      <td>{{ track.title }}</td>
  </tr>
</table>

  <div ng-class="{ 
       selected: selected,
       'track-is-stopped': trackState === 'stop',
       'track-is-playing track-is-paused': trackState === 'pause',
       'track-is-playing': trackState === 'play',
       'track-is-playing track-is-buffering': trackState === 'buffering'           
     }" 
     ng-repeat="track in tracks"
     track>{{ track.title }} 
</div>

I want to control this part in my directive: 我想在我的指令中控制这一部分:

      ng-class="{
        'track-is-stopped': trackState === 'stop',
        'track-is-playing track-is-paused': trackState === 'pause',
        'track-is-playing': trackState === 'play',
        'track-is-playing track-is-buffering': trackState === 'buffering'
      }"

How to do that? 怎么做? It has to work with any element and has to work with any existing ng-class attribute (so I need to extend the current attribute): 它必须与任何元素一起使用,并且必须与任何现有的ng-class属性一起使用(因此我需要扩展当前属性):

ng-class="{ selected: selected }"
  1. Create getClass() in the directive's controller: 在指令的控制器中创建getClass()

     // ... controller: function ($scope) { $scope.getClass = function () { return { 'track-is-stopped': $scope.trackState === 'stop', 'track-is-playing track-is-paused': $scope.trackState === 'pause', 'track-is-playing': $scope.trackState === 'play', 'track-is-playing track-is-buffering': $scope.trackState === 'buffering' }; } } 
  2. Call it in the view: 在视图中调用它:

     <div ng-class="getClass()"> 
  3. You can also safely clean the class object from duplicate classes: 您还可以安全地从重复的类中清除类对象:

     // ... return { 'track-is-stopped': $scope.trackState === 'stop', 'track-is-paused': $scope.trackState === 'pause', 'track-is-playing': $scope.trackState === 'play', 'track-is-buffering': $scope.trackState === 'buffering' } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM