Skip to content Skip to sidebar Skip to footer

Use Window.open In A Directive

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

Solution 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:

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

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

Solution 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.

Post a Comment for "Use Window.open In A Directive"