AngularJS 获取绑定到指令值的服务承诺的结果
AngularJS Getting results of service promise to bind to directive value
在我看来,我有以下指令:
<line-chart data="buildData(id)" options="buildOptions(id)" />
在我的控制器中我有:
var onGetData = function (response) {
return response.data;
}
$scope.buildData = function(id) {
dataService.getDataById(id).then(onGetData);
}
在我的指令中我有:
function lineChartLink($http){
return function(scope, element, attrs) {
chart.bindData(scope.data);
}
}
现在,我的问题是,如何获取折线图指令所需的数据?
你需要在这里做出选择。
如果要将数据传递给指令,则在数据可用之前不应调用指令。您可以使用简单的 ng-if
:
轻松做到这一点
$scope.buildData = function(id) {
dataService.getDataById(id).then(function(response) {
$scope.data = response.data
});
};
$scope.buildData(someId);
并且在视图中:
<line-chart ng-if="data" data="data" ... />
或者您可以将承诺传递给指令,指令应调用 then()
承诺以在可用时获取数据:
var onGetData = function (response) {
return response.data;
};
$scope.buildData = function(id) {
// note the return here. Your function must return something:
// the promise of data
return dataService.getDataById(id).then(onGetData);
};
function lineChartLink($http){
return function(scope, element, attrs) {
scope.data.then(function(theActualData) {
chart.bindData(theActualData);
});
};
}
并且在视图中:
<line-chart data="buildData(id)" ... >
或者,第三种方案,你可以把id传给指令而不是数据,让指令自己去获取数据。
在我看来,我有以下指令:
<line-chart data="buildData(id)" options="buildOptions(id)" />
在我的控制器中我有:
var onGetData = function (response) {
return response.data;
}
$scope.buildData = function(id) {
dataService.getDataById(id).then(onGetData);
}
在我的指令中我有:
function lineChartLink($http){
return function(scope, element, attrs) {
chart.bindData(scope.data);
}
}
现在,我的问题是,如何获取折线图指令所需的数据?
你需要在这里做出选择。
如果要将数据传递给指令,则在数据可用之前不应调用指令。您可以使用简单的 ng-if
:
$scope.buildData = function(id) {
dataService.getDataById(id).then(function(response) {
$scope.data = response.data
});
};
$scope.buildData(someId);
并且在视图中:
<line-chart ng-if="data" data="data" ... />
或者您可以将承诺传递给指令,指令应调用 then()
承诺以在可用时获取数据:
var onGetData = function (response) {
return response.data;
};
$scope.buildData = function(id) {
// note the return here. Your function must return something:
// the promise of data
return dataService.getDataById(id).then(onGetData);
};
function lineChartLink($http){
return function(scope, element, attrs) {
scope.data.then(function(theActualData) {
chart.bindData(theActualData);
});
};
}
并且在视图中:
<line-chart data="buildData(id)" ... >
或者,第三种方案,你可以把id传给指令而不是数据,让指令自己去获取数据。