我正在尝试写一个指令来绘制barcharts,并且我希望它在每次数据更改时重绘图表。目前,我有这样的:
/* This directive will create a bar chart based on a dataTable.
* It expects the first column of the data table to contain the labels.
* If more than 2 columns (labels plus more than one value) are supplied,
* all bars generated by values in one row will be grouped together, making
* an easy visual comparison (benchmark).
* If the option overlay is supplied, the odd value columns will be drawn
* underneath the even values (Ex [label, col1, col2, col3, col4], with overlay = true will result
* in col1 and col3 to be drawn underneath col2 and col4
*/
angular.module('kapstok').directive('nBarChart', ['$window', '$location', '$parse', '$timeout',
function($window, $location, $parse, $timeout){
return{
restrict: 'E',
scope: true,
link: function(scope, elm, attrs){
// Read all the different parameters givin in the directive declaration.
// If options are not given, they are replaced by their default values.
var dataGetter = $parse(attrs.data);
var data = dataGetter(scope) || undefined;
if(!data){
throw Error("No (valid) data source specified!");
}
// Redraw the table once the table gets updated. However, usually multiple elements
// of the table will be updated at the same time, while the watch will get triggered
// at each update. To prevent this, we give it a timeout of half a second,
// allowing all the updates to be applied before the table is redrawn.
scope.$watch(function(){ return data.getVersion(); }, $timeout(drawChart, 500));
然后,在我的控制我做的:
controlmodule.controller('PrefscanController',['$http', '$scope', 'DataTable', function($http, $scope, DataTable){
$scope.myData = new DataTable();
$scope.myData.addColumn("string", "label");
$scope.myData.addColumn("number", "survey");
$scope.myData.addColumn("number", "benchmark");
$scope.myData.addColumn("number", "break-it");
$scope.myData.addRow(['test', 20, 10, 4]);
$scope.myData.addRow(['test2', 42, 13, 2]);
$scope.hideBenchmark = function(){
console.log("myData.version = ", $scope.myData.getVersion());
$scope.myData.hideColumn(2);
console.log("myData.version = ", $scope.myData.getVersion());
}
从dataTable中,一旦有事情发生变化的所谓“版本”属性增加,所有的功能是什么我想要$手表看看。
在我的模板中,我有一个带有ng-click的按钮,它调用hideBenchmark函数。这个函数确实被调用,dataTable版本被更新,但无论我尝试什么,手表都不会被触发。我试过在我的hideBenchmark函数中添加'true'(寻找对象的不等式),试着看'attrs.data()/ $ scope。$ digest() ','data.version',它们都没有触发手表!我知道我可以在独立于该数据的范围上创建另一个变量,观察并在每次更改数据时都进行更改,但看起来很丑陋,没有必要。
有人知道为什么手表没有被触发,我怎么能做到我想要的?
问候,
莱纳斯
您是否尝试将“数据”放在您的指令范围内,而不是将其从属性中取出? – 2014-11-04 10:46:45