Car*_*gan 0 angularjs angularjs-directive angularjs-service
在我看来,我有以下指令:
<line-chart data="buildData(id)" options="buildOptions(id)" />
Run Code Online (Sandbox Code Playgroud)
在我的控制器中我有:
var onGetData = function (response) {
return response.data;
}
$scope.buildData = function(id) {
dataService.getDataById(id).then(onGetData);
}
Run Code Online (Sandbox Code Playgroud)
在我的指示中,我有:
function lineChartLink($http){
return function(scope, element, attrs) {
chart.bindData(scope.data);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我的问题是,如何获得线图指令所需的数据?
你需要在这里做出选择.
如果要将数据传递给指令,则在数据可用之前不应调用该指令.您可以通过简单的方式轻松完成ng-if:
$scope.buildData = function(id) {
dataService.getDataById(id).then(function(response) {
$scope.data = response.data
});
};
$scope.buildData(someId);
Run Code Online (Sandbox Code Playgroud)
并在视图中:
<line-chart ng-if="data" data="data" ... />
Run Code Online (Sandbox Code Playgroud)
或者您可以将promise传递给指令,并且该指令应该调用then()promise来获取可用的数据:
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);
});
};
}
Run Code Online (Sandbox Code Playgroud)
并在视图中:
<line-chart data="buildData(id)" ... >
Run Code Online (Sandbox Code Playgroud)
或者,第三种解决方案,您可以将id传递给指令而不是数据,并让指令自己获取数据.
| 归档时间: |
|
| 查看次数: |
1826 次 |
| 最近记录: |