2014-01-31 89 views
0

我有一个简单的场景

<thead grid-columns pager-info="pagerInfo" onsort="onSort()"> 
    <tr> 
     <th width="15%"><column sortby='FName'>Name</column></th> 
     <th width="17%"><column sortby='Mobile'>Number</column></th> 
    </tr> 
</thead> 

的想法是,因为我所有的列都需要定义一个onsort,我就可以把它定义一次父。

但是,为什么我的孩子指令(列)没有将它的$parent设置为grid-columns指令?相反,scope.$parent设置为控制器作用域,所以我无法解决如何从我的子指令访问我的父指令作用域。

这两个指令有一个孤立的范围,我的孩子指令transcludes:

ngApp.directive('gridColumns', function() { 
    // Attribute-based wrapper round the columns that allows us to capture the pagerInfo and set a sort handler. 
    return { 
     restrict: 'A', 
     scope: { 
      pagerInfo: '=', 
      onsort: '=' 
     } 
    }; 
}); 

ngApp.directive('column', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     replace: true, 
     scope: { 
      sortby: '@' 
     }, 
     template: "<span><a ng-click='sort()' ... </span>", 
     link: function (scope, el, attrs) { 
      scope.sort = function() { 

       // I want to call scope.$parent.onsort, but scope.$parent is the controller ! 

       // scope.$parent.onsort(scope.sortby); 
      }; 
     } 
    }; 

}); 
+0

可以通过这个网址@ http://stackoverflow.com/questions/20212354/angularjs-accessing-parent-directive-properties-from-child -directives –

回答

1

你可以尝试require

ngApp.directive('column', function() { 
    return { 
     restrict: 'E', 
     transclude: true, 
     replace: true, 
     scope: { 
      sortby: '@' 
     }, 
     template: "<span><a ng-click='sort()' ... </span>", 
     require:"^gridColumns", 
     link: function (scope, el, attrs,gridColumnsController) {//inject gridColumnsController 
      scope.sort = function() { 
       gridColumnsController.onsort(scope.sortby);//call the controller's onsort function. 
      }; 
     } 
    }; 

}); 

更新您的gridColumns揭露onsort

ngApp.directive('gridColumns', function() { 

    return { 
     restrict: 'A', 
     scope: { 
      pagerInfo: '=', 
      onsort: '&' //also update the function binding 
     }, 
     controller:function($scope){ 
      this.onsort = function (sortBy){ 
       $scope.onsort({param:sortBy}); 
      } 
     } 
    }; 
}); 

您的HTML:

<thead grid-columns pager-info="pagerInfo" onsort="onSort(param)"> 

你可以在这个拥有更多的信息:AngularJS - $emit only works within it's current scope?

+0

不错,以前从未遇到过。对于其他人来说,它在这里记录得非常好:http://docs.angularjs.org/guide/directive –

+0

@Matt Roberts:我不确定我是否正确理解你,但我认为你需要将你的函数绑定到让它起作用。 –

+0

谢谢,我从函数中删除了一些代码,以避免发布太多的代码噪声,所以是的,因为它不会工作:) –

相关问题