繁体   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