How to get controller scope from multi-level directives in AngularJS(without $parent)

陌路散爱 提交于 2019-12-06 08:33:34

This issue handle with following codes:

A service for storing the controller scope:

App.service('TableService', function () {
        return {
            MyScope: null
        };
    });

Inject the TableService to dynamic directive(this directive compiles dynamic content):

App.directive('dynamic', function ($compile,TableService) {
    return {
        restrict: 'A',
        replace:true,
        link: function (scope, ele, attrs) {
            scope.$watch(attrs.dynamic, function (html) {
                ele.html(html);
                $compile(ele.contents())(TableService.MyScope);
            });
        }
    };
});

And finally in the controller:

App.controller('ScopeController', function ($scope, $rootScope, $uibModal, 
              $http, $filter, $cookieStore, Common, $cookies,TableService) {
    TableService.myScope = $scope;        
    $scope.runTest = function () {
        return `<input type='button' ng-click='testHtml()' value='Test'/>`;
    }
    $scope.testHtml = function () {
        alert("work");
    }
    $scope.model=someModel;
    $scope.config=someConfig;
    $scope.columns={html: $scope.runTest};
});

After that, the dynamic directive can access controller scope and all dynamic events(like testHtml) will be called even if the directive put in another directive(without using the $parent).

thank you @shaunhusain, huan feng for giving me an idea.

In child controller do something like:

$scope.$broadcast('yourEvent');

In parent controller do the listener:

$scope.$on('yourEvent' , function(){
    //Handle your logic            
});

A special case service

.service('DirectDispatcher', function(){
  return {
    fireMe: angular.noop
  }
});

First directive registers a function callback

.directive(
...
  link:function(DirectDispatcher){
    function myHandler() {window.alert('just testing')}
    DirectDispatcher.fireMe = myHandler;
  }

... );

Second directive fires the function callback

.directive(
...
  link:function(DirectDispatcher){
    DirectDispatcher.fireMe();
  }

...
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!