Keshav Keshav - 6 months ago 423
AngularJS Question

Cannot $uibModal inside directive but accessible in controller

I want to make directive to open a modal. But $uibModal is not defined inside directive .

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 () {
});

}
}
});


How can I use $uibModal inside my directive to open modal ?

Answer

Directive link function is not injectable, it takes fixed set of parameters in fixed order. But you can inject services into directive function itself:

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() {});

        }
    }
});

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