Skip to content

Instantly share code, notes, and snippets.

@geovanisouza92
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save geovanisouza92/bb49e195a6edfbfd3b37 to your computer and use it in GitHub Desktop.

Select an option

Save geovanisouza92/bb49e195a6edfbfd3b37 to your computer and use it in GitHub Desktop.
Angular.js directive example 2
angular.module('myApp')
.factory('ApiClient', ApiClient)
.factory('IndividualResource', IndividualResource)
.directive('evolutionGraph', evolutionGraph);
/* @ngInject */
function ApiClient($http) { // Used to pipe request to Api host, shared with other angular services
var service = {
get: getFn,
},
host = '';
$http.get('/api').then(function(data, status, headers, config) {
host = data.data.host;
});
function getFn(path, params) {
return $http.get(host + '/query/api/v1' + path, params);
}
return service;
}
/* @ngInject */
function IndividualResource($q, ApiClient) {
var service = {
get: getFn,
};
function getFn(o, r) { // o: number, r: string
var d = $q.defer();
ApiClient.get('/individuals', {
method: 'GET',
params: {
format: 'json',
limit: 0,
oper: o,
ref: r,
},
})
.success(function(data, status, headers, config) {
d.resolve(data.objects);
})
.error(d.reject);
return d.promise;
}
return service;
}
/* @ngInject */
function evolutionGraph(IndividualResource) {
var directive = {
restrict: 'EA',
template: '', // empty template, because the Chartist lib generate all svg/css needed...
scope: { // Isolated scope, binding html attributes to variables, again...
oper: '=',
ref: '=',
},
link: linkFn, // Additional data manipulation
};
function linkFn(scope, element, attrs) {
element[0].style.display = 'none'; // I hide the div to avoid FOUC
IndividualResource.get(scope.oper, scope.ref) // One service/factory that uses $http to grab additional data for chart
.then(function(data) {
if (data && data.length) {
element[0].style.display = 'block'; // Show the chart div
buildChart(data, element[0]); // Complex data manipulation
}
});
}
function buildChart(d, e) {
var data = { // variables used by Chartist
labels: data.map(function(it) {
return it.sem;
}),
series: [data.map(function(it) {
return 100 * it.efi;
})],
},
options = {
axisX: {
offset: 20,
},
axisY: {
offset: 40,
labelInterpolationFnc: labelFn,
}
};
function labelFn(it) {
return '' + it + '%';
}
Chartist.Line(e, data, options); // Call the Chartist lib to generate a line chart using 'data' with 'options' and applying on 'e' (div#chart)
}
return directive;
}
<div ng-repeat="(ref, prod) in state.operator.pro">
<paper-shadow class="card-performance" z="1">
<!-- Some informations... -->
<div id="chart" class="ct-chart ct-minor-sixth" evolution-graph oper="state.operator.cod" ref="prod.ref"></div> <!-- The external chart lib (Chartist) draws in #chart. [evolution-graph] marks this as a graph to manipulate data. -->
</paper-shadow>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment