Abhishek
Abhishek

Reputation: 2019

Accessing directive scope from outside controller

I am creating a custom directive in a controller and calling it in ng-repeat as follows:

HTML:

<div ng-controller="TestCtrl">
  <div ng-repeat="page in pages">
   <custom 
    load-data="loadData = fn">
   </custom>
  </div>
</div>  

JS:
In Test directive I am calling loadData as follows:

scope: {
   loadData: "&"
}
controller: ['$scope', '$element', '$timeout', '$filter', function ($scope, $element, $timeout, $filter) {
$scope.loadData({ fn: function(data) {  
 //Data calc.
}});
}  

I am calling loadData from TestCtrl as follows:

App.controller('TestCtrl', function($scope, $http, $timeout, $rootScope) {
 $scope.loadData(data);
}  

I need to call loadData function but it is throwing error as undefined is not a function Is there any way I can access scope of child directive from outside it. I went through few SO questions where it was mentioned that using ng-repeat changes scope, but I was not able to figure out a solution to it. I also tried using $broadcast and $on but that did not help

Could anyone please help me with it.

Thanks in Advance

Upvotes: 0

Views: 770

Answers (1)

meriadec
meriadec

Reputation: 2983

I'm not sure to understand your request.. Your code doesn't make any sense, where is defined your data variable ? (controller: line 2), where is defined your fn function ? (html: line 4).

You got the error undefined is not a function which not surprising me because you never defined $scope.loadData method...

I tried to understand your question and produced this code snippet :

angular.module('demo', []);

angular.module('demo')
  .directive('custom', function () {
    return {
      restrict: 'E',
      template: '<div>{{ data || "loading..." }}</div>',
      scope: {
        loadData: '=',
        page: '='
      },
      link: function (scope) {
        scope.loadData(scope.page, function (data) {
          scope.data = data;
        });
      }
    };
  });

angular.module('demo')
  .controller('MainCtrl', function ($scope, $timeout) {
  
    $scope.loadData = function (page, done) {
      $timeout(function () {
        done('data loaded data from ' + page.name);
      }, 1000);
    };
  
    $scope.pages = [
      { name: 'page 1' },
      { name: 'page 2' },
      { name: 'page 3' }
    ];
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.js"></script>

<div ng-app="demo" ng-controller="MainCtrl">
  
  <div ng-repeat="page in pages">
    <custom load-data="loadData" page="page"></custom>
  </div>
  
</div>

Maybe this could help you.

Upvotes: 1

Related Questions