简体   繁体   English

将自定义控制器传递给angular的指令

[英]Pass custom controller to angular's directive

I have a directive that looks like this 我有一个看起来像这样的指令

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

and its defined this was: 它的定义是:

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

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

    })

is there any way to specify what controller I want to use inside that directive smth like this: 有什么办法可以指定我想在该指令smth中使用哪个控制器,如下所示:

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

As I understood, you have two different functions to call within each controller. 据我了解,每个控制器内都有两个不同的函数可以调用。

I would do like that: 我会这样:

make div with ng-controller="yourControllerName" and use directive inside and just pass function name 使用ng-controller =“ yourControllerName”进行div并在内部使用指令并仅传递函数名称

something like: 就像是:

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

add functionToCall inside directive: 在指令内部添加functionToCall:

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

now use functionToCall() inside directive template in ng-click or ng-submit or anywhere you need 现在在ng-click或ng-submit或您需要的任何位置的指令模板内使用functionToCall()

Hopefully you got my point. 希望你明白我的意思。 Works in our project fine. 在我们的项目中工作正常。

Ok after a bit of googleing found this solution: 经过一番谷歌搜索后找到此解决方案:

.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