2014-01-31 83 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

謝謝,我從函數中刪除了一些代碼,以避免發佈太多的代碼噪聲,所以是的,因爲它不會工作:) –

相關問題