代码之家  ›  专栏  ›  技术社区  ›  Spearfisher

在指令中使用window.open

  •  2
  • Spearfisher  · 技术社区  · 11 年前

    我在试着触发 $window.open(url, windowName, attributes); 在我的angular应用程序中单击ng

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

    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 回复  |  直到 11 年前
        1
  •  5
  •   Alex Choroshin    11 年前

    您不能使用链接注入窗口,您可以简单地使用本机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/

        2
  •  4
  •   Michał    11 年前

    你应该这样做:

    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服务是一个指令依赖项,它将在链接函数中可用。