简体   繁体   English

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

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

Is it possible to pass in a custom controller into custom directive to be able to use the custom directive on the page with different controllers ? 是否可以将自定义控制器传递给自定义指令,以便能够在具有不同控制器的页面上使用自定义指令

I can't find a solution for that on docs.angularjs.org 我无法在docs.angularjs.org上找到解决方案

[Edited] 将帖子

Let's say we have the following directive's defenition: 假设我们有以下指令的定义:

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?
        };
    });

Can I simply overwrite the directive's controller not touching the directive's source code itself? 我可以简单地覆盖指令的控制器而不触及指令的源代码本身吗?

Use custom controller with one HTML template 将自定义控制器与一个HTML模板一起使
Then pass your data from that page to directive. 然后将您的数据从该页面传递给指令。
and use that data in HTML template which is assign in directive or also you can write controller in your directive. 并在指令中指定的HTML模板中使用该数据,或者您也可以在指令中编写控制器。

.controller('myController', function () {

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

Then pass it through HTML to directive 然后通过HTML传递给指令
Use that data in, 使用该数据,

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

Perhaps instead of defining the controller in the directive like you have, you can put it in the html template like: 也许不是像你一样在指令中定义控制器,你可以把它放在html模板中,如:

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

Then I think you will be able to use the directive like: 然后我认为您将能够使用如下指令:

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

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

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