如何在另一个控制器的作用域函数中调用自定义指令

How to call custom directive in scope function of another controller

我是 AngularJS 的新手。谁能举例告诉我如何在另一个控制器的作用域函数中调用自定义指令。

例如我有一个控制器,其功能如下:

angularApp.controller('sample_Ctrl', function ($scope, $http, $timeout, $rootScope, $location) {
     $scope.showReport = function(id) {
     };
});

我创建了一个 customDirective 如下:

var showModalDirective = function ($timeout) {
    return {
        restrict: 'E',
        templateUrl: '/Partials/template1.html',
    };
};
angularApp.directive('showModal', showModalDirective);

那么如何在showReport函数中调用这个指令,如何将id传递给模板URL?

您不能在 controller 中调用 directive。它应该是 service

或者您可以在视图中使用指令:

指令:

var showModalDirective = function ($timeout) {
    return {
        restrict: 'E',
        scope: {
           modalId: '='
        },
        templateUrl: '/Partials/template1.html',
    };
};

angularApp.directive('showModal', showModalDirective);

控制器:

angularApp.controller('sample_Ctrl', function ($scope, $http, $timeout, $rootScope, $location) {

  $scope.showModal = false;

  $scope.showReport = function(id) {
    $scope.showModal = true;
    $scope.modalId = id;
  };
});

查看:

<div ng-if="showModal">
   <show-modal modal-id="modalId"></show-modal>
</div>
showModal 变量为 true.

时调用

showModal 指令

要首先使用您的指令,您需要创建与您的指令同名的 HTML 元素,然后从您的控制器为该指令提供数据。假设你的html页面中有一个div。

<div show-modal>  </div>

然后在此页面上,您的 template1.html 将通过指令进行内部调用,并假设 template1.html 中有一些 html 元素,例如

code in your controller -
angularApp.controller('sample_Ctrl',function() {
     $scope.firstName= "My First Name"
})