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):
<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="{ selected: selected }"
Create getClass()
in the directive's controller:
// ... 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' }; } }
Call it in the view:
<div ng-class="getClass()">
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' }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.