在指令中使用 window.open

Spe*_*her 2 javascript jquery window angularjs

$window.open(url, windowName, attributes);我正在尝试通过 ng-click 在我的角度应用程序中触发

由于 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
            };
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

在我的 HTML 中:

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

由于某种原因,当我单击按钮时,窗口没有打开。我的代码有什么问题吗?

Ale*_*hin 5

您不能使用链接注入窗口,您可以简单地使用本机 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
            };
        }
    };
}]);
Run Code Online (Sandbox Code Playgroud)

html:

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

实例: http: //jsfiddle.net/choroshin/crt45/1/

  • 最好将 $window 服务注入指令而不是使用全局本机 js 窗口,因为它更容易测试 - 您可以为单元测试注入模拟的 $window 服务实现。 (3认同)