Вопрос

I'm still new in Angular but i'm doing some progress.. i think :) I have problem passing json file from controller to directive using isolated scope.

This is my controller which talk to factory "dataArchive":

.controller('graphCtrl', ['$scope', 'dataArchive', function($scope, dataArchive){
    dataArchive.get().then(function(data){
        $scope.getData = data;
    });
}]);

Then i have directive which is using isolated scope.

.directive('dataGraph', function($compile){
    return {
        restrict: 'AE',
        replace: true,
        scope: {
            getArchiveData: '='
        },
        template: '<div id="chartdiv"></div>',
        link: function (scope, element, attrs){
             var dati = scope.getArchiveData;
             console.log(dati);
        };
     };
 });

And this is my HTML:

<div ng-controller="graphCtrl">
    <data-graph get-archive-data="getData"></data-graph>
</div>

In console i always get 'undefined'.

Where i am wrong and is this a good way?

Thanks you all.

Это было полезно?

Решение

Since this code is async:

dataArchive.get().then(function(data){
        $scope.getData = data;
    });

The link function will run before the data is set on getData, and therefore the isolated scope variable will not be set at this time. So, I believe you are seeing a timing issue.

To make sure that your directive binding is correct. Try to set $scope.getData to a static value (e.g. $scope.getData = [{ data: 'value'}]). This should work.

Also, Angular checks for changes (to rebind) based on object reference. So, you might need to define $scope.getData in the controller (outside of the async call). Then you might want to push all the data in (instead of replace the entire object with the assignment).

Hope this helps.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top