2016-05-02 88 views
2

我努力在遞歸編譯自身的嵌套指令中調用父控制器函數。點擊tree-item中的按鈕可以工作一個級別,但在此之後,doctype的變量未定義。嵌套遞歸指令將參數傳遞給父控制器方法

這種類型的問題用React進行了簡單的解決,但我認爲新的範圍正在用每個函數傳遞創建,當我真的只想傳遞來自父類的回調引用時。

我認爲這可以通過發射事件來解決,這是一個壞/好主意?

父控制器的方法:

displayDocument(doc, type) { /* */ } 

向下傳遞到tree指令:

<tree display-document="vm.displayDocument(doc, type)"></tree> 

Tree定義:

function Tree() { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'components/ui/biospecimen/templates/tree.html', 
    scope: { 
     displayDocument: '&', 
    } 
    } 
} 

傳遞給tree-item指令從tree.html

<tree-item display-document="displayDocument(doc, type)"></tree-item> 

TreeItem定義:

function TreeItem($compile) { 
    return { 
    restrict: 'E', 
    replace: true, 
    templateUrl: 'components/ui/biospecimen/templates/tree-item.html', 
    scope: { 
     displayDocument: '&', 
    }, 
    link: (scope, el, attrs) => { 
     el.append($compile([ 
     '<tree',   
      'data-ng-repeat="childType in [\'foo\', \'bar\']"', 
      'display-document="displayDocument(doc, type)"', 
     '></tree>' 
     ].join(' '))(scope)) 
    } 
    } 
} 

然後終於裏面用tree-item

<button data-ng-click="displayDocument({ doc: doc, type: type })">Click</button>  

回答

1

你幾乎沒有。你的問題是,當你從指令中調用一個函數時,你必須傳遞一個對象,就像你將對象從樹項目傳遞給樹時一樣。角然後調用函數樹指令,像這樣:

displayDocument(doc, type) 

的問題是,這一功能也是一個指令裏面!它必須以同樣的方式被調用,就像這樣:

displayDocument({ doc: doc, type: type }) 

因此,如果必須使用一個參數(即對象{doc:doc,type:type})調用樹指令中的函數,那麼當您從樹項調用它時,必須將其寫入模板中所以:

<tree-item display-document="displayDocument(args)"></tree-item> 

(或任何其他名稱代替「ARGS」) 並調用它像這樣:

<button data-ng-click="displayDocument({args: { doc: doc, type: type }})">Click</button> 

我創建了一個工作js fiddle了類似於你的情況

相關問題