Skip to content

Instantly share code, notes, and snippets.

@guilbep
Created March 26, 2014 14:59
Show Gist options
  • Save guilbep/9785316 to your computer and use it in GitHub Desktop.
Save guilbep/9785316 to your computer and use it in GitHub Desktop.
Morris directive
define(['directives/directive-module', 'morris'], function(module, Morris) {
module.directive('xngMorris', function($parse, $compile, $interval) {
return {
restrict: 'A',
scope: true,
controller: function($scope, $element, $attrs, $transclude) {
var morris;
// var isDataSet = false;
$scope.getConf = function(_element, _existing_conf) {
_existing_conf.element = _element;
return _existing_conf;
};
$scope.isMorrisCreated = function() {
if ( !! morris) {
return true;
}
return false;
};
// unused
$scope.deleteMorris = function() {
// not really ok
morris = undefined;
};
// morrisMethod will be "Line" or "Bar"
$scope.createMorris = function(morrisMethod, _conf) {
morris = new Morris[morrisMethod](_conf);
};
$scope.setData = function(data) {
morris.setData(data);
console.log(data);
if (data && data.length > 0) {
}
console.log(morris);
};
},
link: function postLink(scope, element, attrs) {
// get attribute data
var getter = $parse(attrs.data),
setter = getter.assign,
data = getter(scope);
var getterConf = $parse(attrs.conf),
setterConf = getterConf.assign,
conf = getterConf(scope);
// watch changes in those attribute data
var triggerChanges = function() {
// check if value is defined or not and act accordingly
// we now can draw our Morris :)
if ( !! data && !! conf) {
// console.log(conf);
if (data && data.length > 0){
if (!scope.isMorrisCreated()) {
conf = scope.getConf(element, conf);
// maybe we should create the morris once we have some data..?
scope.createMorris(conf.method, conf);
}
scope.setData(data);
}
} else {
if (scope.isMorrisCreated()) {
scope.setData([]);
}
}
};
scope.$watch(attrs.data, function(newValue, oldValue) {
if ( !! newValue) {
data = newValue;
triggerChanges();
}
});
scope.$watch(attrs.conf, function(newValue, oldValue) {
if ( !! newValue) {
conf = newValue;
triggerChanges();
}
});
// init
triggerChanges();
}
};
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment