0

我有这个代码:

.directive('hostelGridBed', function($rootScope){
return {
    restrict: 'E',
    scope: {
      config: '=',
      range: '=',
      days: '='
    },
    link: function(scope, element){

    },
    controller: ['$scope', function($scope){
      $scope.innerStay = '';
      function switchStay(data){
        $rootScope.$broadcast('SwitchStay', {data: data.config});
      };
      $scope.onDropComplete = function(data,evt){
        //$rootScope.$broadcast
        switchStay(data);
        console.log('Drop completo bed!');
      }
    }],
    templateUrl: './js/templates/hostelgridbed.html'
  }
})
.directive('hostelGridDay', function(StaysFactory){
  return {
    restrict: 'E',
    scope: {
      config: '=',
      date: '='
    },
    link: function(scope,element){
    },
    controller: ['$scope','$rootScope', function($scope,$rootScope){
      $scope.switchStay = function(evt, data){
        console.log(data);
        // Here. How can I access this controller's $scope
      }
      $scope.$on('SwitchStay', $scope.switchStay);
    }],
    templateUrl: './js/templates/hostelgridday.html'
  }
})

我从 $broadcast 获取数据 好的,一切都很好。除了我需要从 $scope.switchStay 函数中访问指令的 $scope 之外。有没有办法做到这一点?

4

1 回答 1

0

Actually when you $broadcast or $emit the event from the directive, you could send also the directive's scope as parameter. It should work, but this is actually awful and a really bad practice.

What you have to do in these cases is to add a callback parameter to the directive (&) and provide the switchStay function as callback, and simply trigger it from the directive, passing the parameters that you need to access inside the function.

I hope it makes sense.

于 2017-06-26T20:56:15.520 回答