在指令中编辑/添加ngClass

时间:2014-03-13 11:30:23

标签: javascript angularjs angularjs-directive

我正在尝试创建一个指令来重构一些类操作。

请查看this fiddle

我想在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>

我想在我的指令中控制这部分:

      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'
      }"

怎么做? 它必须与任何元素一起使用,并且必须使用任何现有的ng-class属性(所以我需要扩展当前属性):

ng-class="{ selected: selected }"

1 个答案:

答案 0 :(得分:0)

  1. 在指令的控制器中创建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. 在视图中调用它:

    <div ng-class="getClass()">
    
  3. 您还可以安全地从重复的类中清除类对象:

    // ...
    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'
    }