2015-09-14 128 views
1

我有兩個指令,directiveAdirectiveB都帶有link函數。如何從directiveB調用屬於directiveA的功能?如何從子指令的鏈接函數調用父指令鏈接函數

我有我的代碼,成立迄今的方法是:

angular.module('myApp').directive('directiveA', function() { 
    return { 
     templateUrl: 'directiveA.html', 
     link: function (scope) { 
      scope.directiveAAlert = function() { 
       alert('This is A'); 
      } 
     } 
    } 
}); 

angular.module('myApp').directive('directiveB', function() { 
    return { 
     scope: { 
      onButtonClicked: '=' 
     } 
     templateUrl: 'directiveB.html', 
     link: function (scope) { 
      scope.showAlert = function() { 
       scope.onButtonClicked(); 
      } 
     } 
    } 
}); 

directiveA.html

<directive-b onButtonClicked='directiveAAlert'></directive-b> 

directiveB.html

<button ng-click='showAlert()'></button> 

但是,當我按一下按鈕,我收到一個錯誤,說TypeError: scope.onLogInButtonClicked is not a function at Scope.link.scope.showAlert

如何簡單地定義並從子指令中調用這個相同的函數?

回答

1

您需要使用指令require選項,你可以提其他指令將相同的元件上,或者也可能是使用指令API ^require物業我的父母。當您使用require: ^parentDirective時,將允許您訪問需要它的鏈接功能childDirective中的parentDirective控制器。

此外,你需要糾正你的模板html應該有屬性爲-取代它的​​cammelcase情況分開。

directiveA.html:

<directive-b on-button-clicked='directiveAAlert()'></directive-b> 

directiveB.html

<button ng-click='showAlert()'></button> 

代碼

angular.module('myApp').directive('directiveA', function() { 
    return { 
     templateUrl: 'directiveA.html', 
     link: function (scope) { 
      //code here 
     }, 
     controller: function($scope){ 
      scope.directiveAAlert = function() { 
       alert('This is A'); 
      } 
     } 
    } 
}); 

angular.module('myApp').directive('directiveB', function() { 
    return { 
     scope: { 
      onButtonClicked: '=' 
     }, 
     require: '^directiveA', 
     templateUrl: 'directiveB.html', 
     link: function (scope,element,attrs, ctrl) { 
      scope.showAlert = function() { 
       ctrl.onButtonClicked(); //ctrl has access to the directive a controller. 
      } 
     } 
    } 
}); 
+0

爲什麼遷移'directiveAAlert'到控制器?我只是簡單地將屬性從駱駝案件改成了「按鈕點擊」,並解決了我的問題。 (我不需要創建一個控制器,並需要它在孩子的工作) – roscioli

+0

@roscioli哦..這是工作,因爲你確實在隔離範圍內傳遞該方法..如果你不通過隔離範圍那麼你可以直接調用父指令方法而不用將它傳遞到隔離範圍內。 –

相關問題