繁体   English   中英

是否可以将自定义控制器传入自定义指令?

[英]Is it possible to pass in a custom controller into custom directive?

是否可以将自定义控制器传递给自定义指令,以便能够在具有不同控制器的页面上使用自定义指令

我无法在docs.angularjs.org上找到解决方案

将帖子

假设我们有以下指令的定义:

angular.module('myApp', [])
    .controller('myDirectiveController', function ($scope) {
        $scope.name = 'there, dude';
    })
    .directive('myDirective', function () {
        return {
            restrict: 'E',
            replace: true,
            template: '<div>Hello {{name}}!</div>',
            controller: 'myDirectiveController' // can i overwrite it outside this code?
        };
    });

我可以简单地覆盖指令的控制器而不触及指令的源代码本身吗?

将自定义控制器与一个HTML模板一起使
然后将您的数据从该页面传递给指令。
并在指令中指定的HTML模板中使用该数据,或者您也可以在指令中编写控制器。

.controller('myController', function () {

     // write business logic here
     // take some data which you want to use in directive
 });

然后通过HTML传递给指令
使用该数据,

 .directive('dir', function () {
   return  {
       scope: {
           // collect your data and use it in link
       }    
   };
  });

也许不是像你一样在指令中定义控制器,你可以把它放在html模板中,如:

.directive('myDirective', function () {
    return {
        restrict: 'E',
        replace: true,
        scope: {
            ctrl: '='
        },
        template: '<div ng-controller="{{ctrl}}">Hello {{name}}!</div>'
    };
});

然后我认为您将能够使用如下指令:

<my-directive ctrl="myDirectiveController"></my-directive>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM