首页 > 编程 > JavaScript > 正文

详解AngularJS之$window窗口对象

2019-11-19 14:30:58
字体:
来源:转载
供稿:网友

一个浏览器窗口对象的引用。它是一个全局对象,在window中是全局可用的,但是它导致一些问题。在Angular中也经常通过$window服务提到它,因此它可以被重写、删除及测试。

验证代码:

$window 等同于 window。 (function(){   angular.module('Demo', [])   .controller('testCtrl',["$window",testCtrl]);   function testCtrl($window) {     $window === window;   } }());

$window对象可以用来获取浏览器窗口各项属性(如窗口高度宽度、浏览器版本等等)。

1、问题背景

通过$window对象打印出输入框的内容

2、实现源码

<!DOCTYPE html> <html>   <head>     <meta charset="UTF-8">     <title>AngularJS之$window窗口对象</title>     <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>     <script>       var app = angular.module("winApp",[]);       app.controller("winCon",function($window,$scope){         $scope.phone = "15969569556";         $scope.showPhone = function(){           $window.alert("您输入的手机号是:"+$scope.phone);         };       });     </script>   </head>   <body ng-app="winApp">     <div ng-controller="winCon">       <input type="text" id="phone" maxlength="11" ng-model="phone"/>       <button ng-click="showPhone();">显示手机号</button>     </div>   </body> </html> 

3、实现结果

PS:angularjs中书写window.resize功能

 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <script src="angular.js"></script> <script>  var app = angular.module('myApp', []);  app.controller('myCtrl', function ($scope, $window) {   $scope.default = "hello world";   var w = angular.element($window);   w.bind('resize', function(){    console.log(new Date())   })  }); </script></head><body><div ng-app="myApp" ng-controller="myCtrl"><h1>{{default}}</h1></div></body></html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表