簡體   English   中英

將自定義控制器傳遞給angular的指令

[英]Pass custom controller to angular's directive

我有一個看起來像這樣的指令

<list source="userList" avatar-url="avatarPath" search="search"></list>

它的定義是:

    .directive('list', function($rootScope) {

        return {
            restrict: 'E',
            transclude: true,
            templateUrl: 'templates/list.html',
            scope: {
                source:'=',
                search:'=',
                avatarUrl:'='
            }
        }

    })

有什么辦法可以指定我想在該指令smth中使用哪個控制器,如下所示:

    <list source="userList" avatar-url="avatarPath" search="search" controller="listCtrl"></list>
    <list source="userList" avatar-url="avatarPath" search="search" controller="adminListCtrl"></list>

據我了解,每個控制器內都有兩個不同的函數可以調用。

我會這樣:

使用ng-controller =“ yourControllerName”進行div並在內部使用指令並僅傳遞函數名稱

就像是:

<div ng-controller="listCtrl">
    <list source="userList" avatar-url="avatarPath" search="search" function-to-call="someFunctionNameInUserList()"></list>
</div>
<div ng-controller="adminListCtrl">
    <list source="userList" avatar-url="avatarPath" search="search" function-to-call="someFunctionNameInAdminListCtrl()"></list>
</div>

在指令內部添加functionToCall:

scope: {
    source:'=',
    search:'=',
    avatarUrl:'=',
    functionToCall : '='
}

現在在ng-click或ng-submit或您需要的任何位置的指令模板內使用functionToCall()

希望你明白我的意思。 在我們的項目中工作正常。

經過一番谷歌搜索后找到此解決方案:

.directive('list', function() {

    return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'templates/list.html',
        controller: "@",
        name:'controllerName',
        scope: {
            source:'=',
            search:'=',
            avatarUrl:'='
        }
    }

})

<list source="userList" avatar-url="avatarPath" search="search" controller-name="listCtrl"></list>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM