Search code examples
angularjsangularjs-directiveangularjs-service

AngularJS Getting results of service promise to bind to directive value


In my view I have the following directive:

<line-chart data="buildData(id)" options="buildOptions(id)" />

In my controller I have:

var onGetData = function (response) {
  return response.data;
}

$scope.buildData = function(id) {
  dataService.getDataById(id).then(onGetData);
}

In my directive I have:

function lineChartLink($http){
  return function(scope, element, attrs) {
    chart.bindData(scope.data);
  }
}

Now, my issue is, how do I get the line-chart directive the data it needs?


Solution

  • You need to make a choice here.

    If you want to pass data to the directive, then you shouldn't invoke the directive until the data is available. You can do that pretty easily with a simple ng-if:

    $scope.buildData = function(id) {
        dataService.getDataById(id).then(function(response) {
            $scope.data = response.data
        });
    };
    $scope.buildData(someId);
    

    and in the view:

    <line-chart ng-if="data" data="data" ... />
    

    Or you can pass a promise to the directive, and the directive should call then() on the promise to get the data when available:

    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);
            });
        };
    }
    

    and in the view:

    <line-chart data="buildData(id)" ... >
    

    Or, third solution, you can pass the id to the directive rather than the data, and let the directive get the data by itself.