在指令中使用window.open

时间:2014-03-23 14:35:02

标签: javascript jquery angularjs window

我试图通过ng-click

在我的角应用中触发$window.open(url, windowName, attributes);

由于链接到我模板上的按钮的ng-click,我已经定义了一个指令并将window.open包装在一个函数触发器中:

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
            };
        }
    };
}]);

在我的HTML中:

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

由于某些原因,单击按钮时窗口无法打开。我的代码出了什么问题?

2 个答案:

答案 0 :(得分:4)

你应该这样做:

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
            };
        }
    };
}]);

$ window服务是一个指令依赖项,它将在链接函数中可用。

答案 1 :(得分:3)

您无法使用链接注入窗口,只需使用原生JavaScript 窗口对象

示例:

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>

直播示例:http://jsfiddle.net/choroshin/crt45/1/