1

Within a controller I have an ajax call that populates $scope.main_data. I want to within a directive get that data when it populates. However the two issues I'm having is:

  1. I cannot seem to access $scope.main_data from the directive.
  2. $scope.watch doesn't seem to work because of this.

How can I print the data from the directive once the data arrives?

CONTROLLER:

app.controller('myCtrl', ['$scope','$http',  function($scope, $http) {

$scope.main_data = [];

$http.get("some_url").success( function(data) {
  $scope.main_data = data; 
 });

}]);

DIRECTIVE:

app.directive('myDir', function($compile, $rootScope) {
    return {
        restrict: 'A',
        scope: {
            items: '=items'
        },
        link: function($scope, element, attrs, ctrl) {

           $scope.$watch($scope.main_data ,function(newValue,oldValue){ 

             if (newValue){           
                  console.log($scope.main_data);
             }            

           });

        }
    };
});

HTML:

<div ng-controller="myCtrl">
 <div my-dir>
 <div>
</div>

The directive in the html exists within the controller but for some reason I can't access the controller scope through $scope but $scope.$parent.

1
  • Shouldn't it be $scope.$watch("main_data" ,function(newValue,oldValue){? - Even better, why not pass main_data in as a 2 way binding, then watch that variable instead? Commented Jan 4, 2017 at 22:01

1 Answer 1

1

You've almost got it.

app.directive('myDir', function($compile, $rootScope) {
return {
    restrict: 'A',
    scope: {
        items: '=items'
    },
    link: function($scope, element, attrs, ctrl) {
       $scope.$watch("items",function(newValue,oldValue){ 
         if (newValue){           
              console.log($scope.main_data);
         }            
       });
    }
};
});

And html:

 <div ng-controller="myCtrl">
 <div my-dir items="main_data">
 </div>
 </div>

Even though you can "hack" around and access main_data using series of$parent calls on your scope and using some other methods, just pass it in to your directive with = binding, so it will be updated when controller scope is updated. In fact you don't even need $watch in this case, you will always have actual data.

Sign up to request clarification or add additional context in comments.

3 Comments

This doesn't seem to work since the watch method calls twice on page reload. One with the empty data [] and two with the loaded data.
Anyway it works though if I put - if (newValue && newValue.length != 0){...} God I love javascript......
you can change it to <div myDir items='main_data' ng-if='main_data' ... this way you will only render directive when main_data is available

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.