我创建了一个使用 Morris 绘制条形图的指令。当我对值进行硬编码时,它确实绘制了条形图。但我无法用从 http 响应收到的值绘制图表。我是 javascript、angularjs 等新手。
模块:
var sampleApp = angular.module('sample',[]);
指令:
sampleApp.directive('barchart', function() {
return {
restrict: 'E',
template: '<div></div>',
replace: true,
link: function($scope, element, attrs) {
var data = $scope[attrs.data],
xkey = $scope[attrs.xkey],
ykeys= $scope[attrs.ykeys],
labels= $scope[attrs.labels];
var setData = function(){
console.log('inside setData function');
Morris.Bar({
element: element,
data: data,
xkey: xkey,
ykeys: ykeys,
labels: labels
});
};
// The idea here is that when data variable changes,
// the setData() is called. But it is not happening.
attrs.$observe('data',setData);
}
};
});
Controller :
sampleApp.controller('sampleController',function($scope, $http){
$scope.xkey = 'range';
$scope.ykeys = ['total_tasks', 'total_overdue'];
$scope.labels = ['Total Tasks', 'Out of Budget Tasks'];
$scope.myModel = [
{ range: 'January', total_tasks: 5, total_overdue: 5 },
{ range: 'January', total_tasks: 35, total_overdue: 8 },
{ range: 'January', total_tasks: 20, total_overdue: 1 },
{ range: 'January', total_tasks: 20, total_overdue: 6 }
];
$http({method: 'GET', url: '../test/executeTest'}).
success(function(data, status, headers, config) {
// here I would populate myModel with values from above url.
// But for simplicity, I'm just hardcoding the values(changed slightly) again.
$scope.myModel = [
// changing just one value in first row.
{ range: 'January', total_tasks: 25, total_overdue: 5 },
{ range: 'January', total_tasks: 35, total_overdue: 8 },
{ range: 'January', total_tasks: 20, total_overdue: 1 },
{ range: 'January', total_tasks: 20, total_overdue: 6 }
];
console.log('success ' + $scope.myModel[0].total_tasks);
}).
error(function(data, status, headers, config) {
console.log('error');
});
});
html:
<html>
<head>
<script src="lib/jquery-1.8.2.min.js"></script>
<script src="lib/angular.min.js"></script>
<script src="lib/raphael-min.js"></script>
<script src="lib/morris.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body ng-app="sample" ng-controller="sampleController">
<barchart xkey="xkey" ykeys="ykeys" labels="labels" data="myModel"></barchart>
</script>
</body>
</html>
我在某处读到,如果值不包含像 {{..}} 这样的大括号,我不应该使用观察者。但我不知道如何用观察者或任何其他东西来修复它。
最佳答案
回答https://stackoverflow.com/a/22063220/2266630 - $摘要问题
替换
$scope.$apply()
对于
$timeout(function(){
$scope.$apply();
});
[1] - $超时 - https://coderwall.com/p/udpmtq
[2] - $申请 - http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
关于javascript - angularjs morris 指令从 json 休息创建图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22015677/