2014-10-16 47 views
0

我有這個網站結合在AngularJS

<div ng-app="myApp"> 
    <parent> 
     <child></child> 
    </parent> 
</div> 

transclude和指導繼承和下面的角碼

var myApp = angular.module('myApp',[]); 

myApp.directive('parent', function() { 
return { 
    transclude: true, 
    link: function(scope, element, attrs) { 
     scope.getContent = function() { 
      console.log('called getContent'); 
     } 
    }, 
    restrict: 'E', 
    template: '<span>parent <span ng-transclude></span></span>' 
} 
}); 

myApp.directive('child', function() { 
return { 
    restrict: 'E', 
    scope:true, 
    template: '<div>child</div>', 
    link: function(scope, element, attrs) { 
     scope.getContent(); 
    } 
} 
}); 

的jsfiddle以上是here

我在這個例子中的問題是我可以看到繼承工作和跨越孤立工作,但當我嘗試將兩者結合起來時,子指令不知道父範圍,他函數getContent。所以沒有console.log,並且在那之前,scope.getContent未定義的子指令錯誤。

我意識到,這可能是孩子的指令不再是一個孩子被橫掃,所以我想我需要開始玩編譯方法中的post和prelink函數?還是我需要在父級定義一個自定義transclude函數?

的代碼或進一步閱讀任何指針讚賞 - 我已閱讀並在這裏對這種事情類似的問題,但我發現很難遵循,希望有人能解決我的Hello World的kickstart我的理解

在此先感謝

回答

2

你應該閱讀這篇文章:http://www.undefinednull.com/2014/07/07/practical-guide-to-prelink-postlink-and-controller-methods-of-angular-directives/

基本上,你的孩子的環節是家長一個之前調用。你想要做的就是使用你的父母預鏈接功能,這樣scope.getContent被定義爲孩子被鏈接的beforte。

link: { 
    pre: function (scope, element, attrs) { 
     scope.getContent = function() { 
      console.log('called'); 
     } 
    } 
} 

的jsfiddle:http://jsfiddle.net/floribon/gpwasrkz/3/

+0

好的,謝謝。我沒有意識到,你可以使用這樣的前後鏈接方法,我認爲你必須在編譯方法 – alfonsob 2014-10-16 19:20:33

+0

中定義它們,這標誌着這是一個正確的答案,因爲它有助於理解在這種情況下事件發生的順序,這是我的主要懷疑爲什麼這不是爲我工作 - 謝謝floribon – alfonsob 2014-10-16 19:29:38

2

已經在文檔看看"Creating Directives that Communicate"。也許這是您嘗試實現的解決方案。您可以要求父母控制器並將其稱爲功能:

var myApp = angular.module('myApp', []); 

myApp.directive('parent', function() { 
    return { 
     transclude: true, 
     controller: function ($scope) { 
      this.getContent = function() { 
       console.log('called') 
      } 
     }, 
     link: function (scope, element, attrs) {}, 
     restrict: 'E', 
     template: '<span>parent <span ng-transclude></span></span>' 
    } 
}); 

myApp.directive('child', function() { 
    return { 
     restrict: 'E', 
     scope: true, 
     require: '^parent', 
     template: '<div>child</div>', 
     link: function (scope, element, attrs, ctrl) { 
      ctrl.getContent(); 
     } 
    } 
}); 

請參閱this fiddle

+0

也感謝這種替代方法+1 – alfonsob 2014-10-16 19:25:33