我是Angularjs的新手。我想获取我的自定义指令的属性,并使用响应进行 http 调用并生成图形。
<lineGraph query="select * from load.webserver[0-9]"></lineGraph> <!-- query is sent over http to db -->
我的 angularjs 代码是这样的,
var app = angular.module('app', []);
//Factory to get data from influxDB over http
app.factory('influxFactory', ['$q', function($q) {
.... code for querying db using http
})
//
app.controller('mycontroller', [ '$scope', 'influxFactory', function($scope, influxFactory){
scope.constructGraphData = function(query){
influxFactory.getDataFromDBOverHTTP().then(function(data){
... graph data is constructed here
$scope.graphdata = constructed_data // graph data to be plotted is stored and need to be given to drawFlotChart
})
}
})
app.directive('lineGraph', function () {
function drawFlotChart(graphdata){
... flot code to draw the graph
}
return {
restrict: 'E',
templateUrl: 'templates/linegraph.html',
link: function(scope, elt, attr){
// Take value of "query" in <myLineDirective query="load.we...
scope.constructGraphData(attr.query)
/*** How do I capture the $scope.graphdata here ... its "undefined" since http response takes time. Need help. ***/
}
})
我不能使用 $watch('graphdata', function()),因为'graphdata'在构造时被多次修改,因此 function() 被多次执行我尝试使用"范围:{"但没有运气。 有人可以帮忙吗?
您可以在
控制器的constructGraphData
函数中使用$q
。在函数的开头创建一个延迟对象,返回其承诺并在准备就绪时constructed_data
解析。然后,在您的指令中,调用 scope.constructGraphData(attr.query).then(...)
以使用该graphdata
。