我正在尝试通过创建 Angular JS 指令来使用 Morris JS 创建图形。我的指令代码是:
Reporting.directive('morrisLine', function(){
return {
restrict: 'EA',
template: '<div id="call-chart">test2</div>',
scope: {
data: '=', //list of data object to use for graph
xkey: '=',
ykey: '='
},
link: function(scope,element,attrs){
new Morris.Line({
element: element,
data: [
{ year: '2008', value: 20 },
{ year: '2009', value: 10 },
{ year: '2010', value: 5 },
{ year: '2011', value: 5 },
{ year: '2012', value: 20 }
],
xkey: '{year}',
ykey: ['value'],
});
}
};
});
我在浏览器上检查控制台时收到的错误代码是:
TypeError: Cannot call method 'match' of undefined
at Object.t.parseDate (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:9523)
at n.eval (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:3297)
at n.t.Grid.r.setData (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:3888)
at n.r (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:1680)
at new n (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:11953)
at link (http://127.0.0.1:8000/static/js/app/directives/directives.js:94:20)
at j (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:43:157)
at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:463)
at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:480)
at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:480) <div morris-line="" class="ng-isolate-scope ng-scope" style="position: relative;">
错误代码指向的部分是说
element : element,
我是 Angular JS 和指令的新手,希望有人能为我指出正确的方向来处理这个问题。谢谢!
最佳答案
我就是这样处理莫里斯图的。示例是条形图:
sampleApp.directive('barchart', function() {
return {
// required to make it work as an element
restrict: 'E',
template: '<div></div>',
replace: true,
// observe and manipulate the DOM
link: function($scope, element, attrs) {
var data = $scope[attrs.data],
xkey = $scope[attrs.xkey],
ykeys= $scope[attrs.ykeys],
labels= $scope[attrs.labels];
Morris.Bar({
element: element,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels
});
}
};
});
然后你可以将它与这个元素一起使用:
<barchart xkey="xkey" ykeys="ykeys" labels="labels" data="myModel"></barchart>
其中 myModel 是要传入指令的数据数组,它应该具有与莫里斯图表兼容的正确格式。仔细查看该对象是如何在指令中的“链接”函数中传递的。
这是一个完整的工作示例:http://jsbin.com/ayUgOYuY/5/edit?html,js,output
关于javascript - 如何在 Angular JS 中为 Morris JS 图创建指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20322956/