How do I share scope between two directives in AngularJS?

前端 未结 4 1006
夕颜
夕颜 2020-12-05 08:18

I want to share the $scope between the following two directives:

One23SRCApp.directive(\'directive1\',function() {
    return {
        restrict         


        
4条回答
  •  执笔经年
    2020-12-05 08:45

    The sample of Chandermani is working. However this way you still have to assign the attribute on your directive and its not isolated anymore. This is a pollution on the scope...

    My advice is to share your isolated scope by using the controller an passing it this way. Your house, your code! Think before you code but most of all... ENJOY!

    One23SRCApp.directive('directive1',function() {
        return {
             restrict: "A",
             scope: true,
             controller : function($scope){
                  $scope.tableconfig= {};
                  this.config = function (){ 
                       return $scope.tableconfig;
                  }
             },
             link: function (scope, element, attrs) {
                 scope.tableconfig.tablename= "table";
             }
        }
    });
    
    
    One23SRCApp.directive('directive2',function() {
         return {
               restrict: "A",
               //^ -- Look for the controller on parent elements, not just on the local scope
               //? -- Don't raise an error if the controller isn't found
               require: "^directive1",
               link: function (scope, element, attrs) {
                   var tablename = scope.config().tablename;
               }
        }
    });
    

    Usage

    
    

提交回复
热议问题