简体   繁体   中英

getting data in child directive from parent directive in Angular JS

I have a parent directive in which its controller makes a call through a service to get some data.

sharedService.getData(options).then(function(data){
    $scope.data = data;
});

Now i need this data in my child controller.

What i have already tried are the ff: 1) Through $timeout i get the data after sometime but it doesn't seem a good solution impacting performance

2) watchCollection() - i watched if newValue !== oldValue problem being the data is huge so it takes a toll of performance

Now the issue i'm getting is the child directive gets executed after parent BUT before the data comes back from the service and i'm not able to get that data in my child directive via $scope.data.

Is there any solution to get data from parent directive to child directive when i have to wait for data to come in parent?

You can include your parent directive controller in your child directive by using require .

angular.module('myApp', [])
.directive('dirParent', function() {
  return {
    restrict: 'E',
    scope: {},
    controller: ['$scope', function($scope) {

          }],

  };
})
.directive('dirChild', function() {
  return {
    require: '^dirParent', // include directive controller
    restrict: 'E',
    scope: {

    },
    link: function(scope, element, attrs, paretCtrl) {
      var data = paretCtrl.getMyData();
    }
  };

})

It's always a best to use service for communication and and business logic. Here is an example. Please check. This might solve your problem.

 // Code goes here angular.module('app', []) .factory('messageService', function() { return { message: null } }) .directive('parentDir', function() { return { scope: {}, //isolate template: '<input type="text" ng-model="PDirInput"/><button ng-click="send()">Send</button>', controller: function($scope, messageService) { $scope.send = function() { messageService.message = $scope.PDirInput; } } } }) .directive('childDir', function() { return { scope: {}, //isolate template: '<code>{{CDirInput.message}}</code>', controller: function($scope, messageService) { $scope.CDirInput = messageService; } } }) 
 <!DOCTYPE html> <html ng-app="app"> <head> <script data-require="angular.js@*" data-semver="2.0.0-alpha.31" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> <script src="script.js"></script> </head> <body> <HR/>Parent Directive <parent-dir></parent-dir> <br/> <HR/>Child Directive <child-dir></child-dir> <HR/> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM