diff --git a/src/chart.js b/src/chart.js index 2840081..afbd479 100644 --- a/src/chart.js +++ b/src/chart.js @@ -4,32 +4,61 @@ angular.module('ui.chart', []) restrict: 'EACM', template: '
', replace: true, - link: function (scope, elem, attrs) { - var renderChart = function () { - var data = scope.$eval(attrs.uiChart); - elem.html(''); - if (!angular.isArray(data)) { - return; - } - - var opts = {}; - if (!angular.isUndefined(attrs.chartOptions)) { - opts = scope.$eval(attrs.chartOptions); - if (!angular.isObject(opts)) { + scope: { + data: "=uiChart", + opts: "=chartOptions" + }, + controller: ["$scope", "$element", "$attrs", function($scope, $element, $attrs) { + $scope.createGraph = function() { + if (!angular.isUndefined($attrs.chartOptions)) { + if (!angular.isObject($scope.opts)) { throw 'Invalid ui.chart options attribute'; } } - - elem.jqplot(data, opts); + return $element.jqplot( + $scope.data, + $scope.opts || {} + ).data("jqplot"); + }; + $scope.replot = function() { + var options = $scope.opts || {}; + options.data = $scope.data; + options.clear = true; + $scope.jqplot.replot(options); + }; + $scope.renderChart = function() { + if (angular.isArray($scope.data)) { + if ($scope.jqplot) { + $scope.replot(); + } else { + $scope.jqplot = $scope.createGraph(); + } + } else { + if ($scope.jqplot) { + $scope.destroy(); + } + } + }; + $scope.assignEventHandlers = function() { + $scope.$watch("data", function () { + $scope.renderChart(); + }, true); + $scope.$watch("opts", function () { + $scope.renderChart(); + }); + $element.on("$destroy", function() { + $scope.destroy(); + }); + }; + $scope.destroy = function() { + if ($scope.jqplot) { + $scope.jqplot.destroy(); + $scope.jqplot = null; + } }; - - scope.$watch(attrs.uiChart, function () { - renderChart(); - }, true); - - scope.$watch(attrs.chartOptions, function () { - renderChart(); - }); + }], + link: function (scope, elem, attrs, ctrl) { + scope.assignEventHandlers(); } }; - }); \ No newline at end of file + }); diff --git a/test/chart.spec.js b/test/chart.spec.js index aac4c4b..c5fb223 100644 --- a/test/chart.spec.js +++ b/test/chart.spec.js @@ -130,4 +130,4 @@ describe('uiChart Directive', function () { expect(element.html()).toBe(''); expect(element[0].children.length).toBe(0); }); -}); \ No newline at end of file +});