不能在指令中使用$ uibModal但可以在控制器中访问

Kes*_*hav 5 angularjs angularjs-directive bootstrap-modal

我想制定一个指令来打开一个模态.但$ uibModal未在指令内定义.

var app=angular.module("app",['ui.bootstrap']);

app.controller('AppCtrl', function ($scope, $uibModal) {
    console.log("$uibModal controller",$uibModal);//getting object
});

app.directive('showPopUp',function() {
    return {
        restrict: 'EA',
        link: function(scope, el, attrs,$uibModal) {
            console.log("$uibModal",$uibModal);//undefined here
                var modalInstance = $uibModal.open({
                  animation: $scope.animationsEnabled,
                  templateUrl: 'popup.html',
                });

                modalInstance.result.then(function (selectedItem) {
                  scope.selected = selectedItem;
                }, function () {
                });

        }  
    }
});
Run Code Online (Sandbox Code Playgroud)

如何在我的指令中使用$ uibModal来打开模态?

dfs*_*fsq 3

指令链接函数不可注入,它以固定顺序采用固定参数集。但是您可以将服务注入指令函数本身:

app.directive('showPopUp', function($uibModal) {
    return {
        restrict: 'EA',
        link: function(scope, el, attrs) {

            var modalInstance = $uibModal.open({
                animation: scope.animationsEnabled,
                templateUrl: 'popup.html',
            });

            modalInstance.result.then(function(selectedItem) {
                scope.selected = selectedItem;
            }, function() {});

        }
    }
});
Run Code Online (Sandbox Code Playgroud)

演示: http://plnkr.co/edit/jwNOM94DtyRIXTdhvJmy? p=preview