2016-11-29 74 views
1

我試圖通過簡單地附加一個屬性指令來擴展指令的任何指令的功能,但我無法獲取定義屬性的元素的作用域。從屬性指令獲取元素範圍

例如,我有這樣的模板:

<div class="flex-item-grow flex-item flex-column report-area"> 
    <sv-report sv-reloadable id="reportId"></sv-report> 
</div> 

這裏,sv-reloadablesv-report一些默契,但sv-report不知道sv-reloadable

我定義爲sv-reloadable

angular 
    .module('sv-reloadable', [ 
     'sv.services', 
    ]) 
    .directive('svReloadable', function(reportServices, $timeout) { 
     return { 
      restrict: 'A', 
      controller: function($scope, $timeout) { 
       $scope.$on('parameter-changed', function(evt, payload) { 
        evt.stopPropagation(); 
        $scope.viewModel = getNewViewModel(payload);/* hit the server to retrieve new data */ 
       }); 
      } 
     }; 
    }); 

現在,$scopesv-reloadablesv-report範圍。我希望sv-reloadable能夠將偵聽器附加到sv-report的作用域,並將該作用域的屬性換出。我知道有可能抓住兄弟範圍,但是當試圖找出它所附帶的元素時會導致問題。

我嘗試以下操作:

link: function(scope, element, attrs) { 
    ele = element; 
    var actualScopyThingy = element.scope(); 
}, 

,我曾假設會給我的屬性是上定義的元素的範圍,但很可惜,它還是返回元素的範圍。

如果它是重要的,sv-report被定義爲以下,但我希望能夠保持相同的(因爲sv-reloadable將被連接到許多不同的元素,所有這些viewModel定義其範圍)

return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'sv-report/sv-report.tpl.html', 
    scope: { 
     id: '=', 
     reportParameters: '=' 
    }, 
    controller: function ($scope, svAnalytics) { 
     /* unrelated code here */ 
    }, 
    link: function(scope, element, attrs) { 
     initialLoadReport(scope); 
    } 
}; 

回答

1

了一下週圍挖掘後,isolateScope()就是我後(而不是scope())。 sv-reloadable的指示變爲:

return { 
     restrict: 'A', 
     link: function(scope, element, attrs) { 
      var elementScope = element.isolateScope(); 
      elementScope.$on('parameter-changed', function(evt, payload) { 
       ... 
      }); 
     } 
    };