Use window.open in a directive

2019-08-09 04:18发布

问题:

I am trying to trigger $window.open(url, windowName, attributes); in my angular app with a ng-click

I have defined a directive and wrap window.open in a function trigger thanks to an ng-click linked to a button on my template:

myApp.directive('myModal', ['$log', function ($log, $window) {
    return {
        restrict: 'E',

        templateUrl: 'modal-tpl',

        replace: true,

        transclude: true,

        link: function (scope, window) {
            scope.openWindow = function(){
                window.open('https://myLink', 'Google', 'width=500,height=400');
               //some other code
            };
        }
    };
}]);

And in my HTML:

   <button type="submit" class="cta main right ease"ng-click="openWindow()">open window</button>

For some reason the window doesn't open when I click on the button. What's wrong with my code?

回答1:

You cannot inject window using link, you can simply use the native JavaScript window object

example:

js:

var app=angular.module('App', []);
app.directive('myModal', ['$log', function ($log) {
    return {
        restrict: 'EA',

        link: function (scope,element) {
            scope.openWindow = function(){
                window.open('https://myLink', 'Google', 'width=500,height=400');
               //some other code
            };
        }
    };
}]);

html:

<div ng-app="App"  >
 <button type="submit" my-Modal="" class="cta main right ease"ng-click="openWindow()">open window</button>
</div>

Live Example: http://jsfiddle.net/choroshin/crt45/1/



回答2:

You should do it like this:

myApp.directive('myModal', ['$log', '$window', function ($log, $window) {
    return {
        restrict: 'E',

        templateUrl: 'modal-tpl',

        replace: true,

        transclude: true,

        link: function (scope) {
            scope.openWindow = function(){
                $window.open('https://www.google.pl', 'Google', 'width=500,height=400');
               //some other code
            };
        }
    };
}]);

the $window service is a directive dependency, it will be available inside link function.