Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to render custom legend text per item #982

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions spec/legend-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,23 @@ describe("dc.legend", function() {
legendItem(0).on("click").call(legendItem(0)[0][0], legendItem(0).datum());
expect(chart.selectAll("path.line").size()).toBe(3);
});

describe('with .legendText()', function() {
beforeEach(function() {
chart.legend(dc.legend().legendText(function(d, i) {
var _i = i + 1;

return _i + '. ' + d.name;
}));
chart.render();
});

it('should label the legend items with the names of their associated stacks', function() {
expect(legendLabel(0).text()).toBe("1. Id Sum");
expect(legendLabel(1).text()).toBe("2. Value Sum");
expect(legendLabel(2).text()).toBe("3. Fixed");
});
});
});

describe('legends with dashed lines', function () {
Expand Down
29 changes: 27 additions & 2 deletions src/legend.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ dc.legend = function () {
_horizontal = false,
_legendWidth = 560,
_itemWidth = 70,
_autoItemWidth = false;
_autoItemWidth = false,
_legendText = dc.pluck('name');

var _g;

Expand Down Expand Up @@ -82,7 +83,7 @@ dc.legend = function () {
}

itemEnter.append('text')
.text(dc.pluck('name'))
.text(_legendText)
.attr('x', _itemHeight + LABEL_GAP)
.attr('y', function () {
return _itemHeight / 2 + (this.clientHeight ? this.clientHeight : 13) / 2 - 2;
Expand Down Expand Up @@ -210,5 +211,29 @@ dc.legend = function () {
return _legend;
};

/**
#### .legendText([legendTextFunction])
Set or get the legend text function. The legend widget uses this function to render
the legend text on each item. If no function is specified the legend widget will display
the names associated with each group.

Default: dc.pluck('name')

```js
// create numbered legend items
chart.legend(dc.legend().legendText(function(d, i) { return i + '. ' + d.name; }))

// create legend displaying group counts
chart.legend(dc.legend().legendText(function(d) { return d.name + ': ' d.data; }))
```
**/
_legend.legendText = function (_) {
if (!arguments.length) {
return _legendText;
}
_legendText = _;
return _legend;
};

return _legend;
};