我是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()被执行多次 我尝试过“范围:{”但没有运气。 有人可以帮忙吗?
答案 0 :(得分:0)
您可以在控制器的$q
功能中使用constructGraphData
。在函数开头创建一个延迟对象,返回其承诺,并在constructed_data
准备就绪后解析。然后,在您的指令中,致电scope.constructGraphData(attr.query).then(...)
以使用graphdata
。