AngularJS 别有洞天的内置服务

前端之家收集整理的这篇文章主要介绍了AngularJS 别有洞天的内置服务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

学习要点

@H_301_3@
  • 全局对象服务
  • 异常处理
  • 处理危险数据
  • 使用NG表达式和指令
  • 一、全局对象服务
    为什么使用全局对象服务?
    使得测试更加简单。

    1.访问window对象

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <button class="btn btn-primary" ng-click="displayAlert('clicked')">Click Me</button>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",[]) .controller("defaultCtrl",function ($scope,$window) { // 数据模型 $scope.displayAlert = function (msg) { $window.alert(msg); } }) </script>
    </body>
    </html>

    2.访问document对象

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <button class="btn btn-primary">Click Me</button>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",$window,$document) { // 数据模型 $scope.displayAlert = function (msg) { $window.alert(msg); } $document.find("button").on("click",function (e) { $scope.displayAlert(e.target.innerText); }) }) </script>
    </body>
    </html>

    3.使用Interval 和 Timeout

    <!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <Meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="panel panel-default"> <div class="panel-heading">Time</div> <div class="panel-body">The Time is: {{time}}</div> </div> <script type="text/javascript" src="js/angular.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript"> // 使用指令 angular.module("exampleApp",$interval) { // 数据模型 $interval(function () { $scope.time = new Date().toTimeString(); },2000); }) </script> </body> </html>

    4.访问URL

    1)使用HTML5 MRUL

    <!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <Meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="panel panel-default"> <div class="panel-heading">URL</div> <div class="panel-body"> <P>The URL is: {{url}}</P> <div class="btn-group"> <button class="btn btn-primary" ng-click="setUrl('reset')">Reset</button> <button class="btn btn-primary" ng-click="setUrl('path')">Path</button> <button class="btn btn-primary" ng-click="setUrl('hash')">Hash</button> <button class="btn btn-primary" ng-click="setUrl('search')">Search</button> <button class="btn btn-primary" ng-click="setUrl('url')">URL</button> </div> </div> </div> <script type="text/javascript" src="js/angular.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript"> // 使用指令 angular.module("exampleApp",[]) // HTML5 MRUL .config(function($locationProvider) { // 判断是否支持window.history if (window.history && history.pushState) { $locationProvider.html5Mode(true); } }) .controller("defaultCtrl",$location) { // $location所定义的事件---URL被改变后触发 $scope.$on("$locationChangeSuccess",function (event,newUrl) { $scope.url = newUrl; }) $scope.setUrl = function (component) { switch (component) { // 重置URL case "reset": $location.path(""); $location.hash(""); $location.search(""); break; // 路径 case "path": $location.path("/cities/london"); break; // 散列 case "hash": $location.hash("north"); break; // 查询字符串 case "search": $location.search("select","hotels"); break; // 完整路径 case "url": $location.url("/cities/london?select=hotels#north"); break; } } }) </script> </body> </html>

    2)滚到$location散列的位置

    <!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <Meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="panel panel-default"> <div class="panel-heading">URL</div> <div class="panel-body"> <P id="top">This is the top.</P> <button class="btn btn-primary" ng-click="show('bottom')">Go to Bottom</button> <p> <ul> <li ng-repeat="item in items">{{item}}</li> </ul> </p> <p id="bottom">This is the bottom.</p> <button class="btn btn-primary" ng-click="show('top')">Go to Top</button> </div> </div> <script type="text/javascript" src="js/angular.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript"> // 使用指令 angular.module("exampleApp",[]) // HTML5 MRUL .config(function($anchorScrollProvider) { // 禁用自动滚动 $anchorScrollProvider.disableAutoScrolling(); }) .controller("defaultCtrl",$location,$anchorScroll) { $scope.itemCount = 50; $scope.items = []; for(var i = 0; i < $scope.itemCount; i++) { $scope.items[i] = "Item " + i; } $scope.show = function (id) { $location.hash(id); // 只允许向下滚动 if (id == "bottom") { $anchorScroll(); } } }) </script> </body> </html>

    5.执行日志

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",[]) .factory("logService",function ($log) { var messageCount = 0; return { log : function (msg) { $log.log("Click count: " + messageCount++ + ") " + msg); } } }) .controller("defaultCtrl",function ($document,logService) { $document.on("click",function () { logService.log("click me"); }) }) </script>
    </body>
    </html>

    二、异常处理
    1.为什么要使用异常?
    异常一般分为两大类:一种是在编码和测试中产生的;一种是你的应用程序公布用户所看见的。
    因此为了让我们的程序运行的更好,我们有必要使用异常来处理和报告错误
    2.创建自定义异常处理器

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <div class="panel panel-default">
            <div class="panel-body">
                <button class="btn btn-primary" ng-click="throwEx()">Throw Exception</button>
            </div>
        </div>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",myException) { $scope.throwEx = function () { try { throw new Error("Triggered Exception"); } catch (ex) { // ex.message == Triggered Exception myException(ex,"Button Click"); } } }) // 自定义异常处理器 .factory("myException",function ($log){ return function (exception,cause) { $log.error("Message: " + exception.message + " (Cause: " + cause + ")"); } }); </script>
    </body>
    </html>

    三、处理危险数据
    1.为什么使用危险数据服务?
    在web应用程序中,攻击的行为很正常的,他们可能会发送一段不友好的代码来扰乱你精心的布局,这让人感觉很糟糕!
    2.危险数据

    <!DOCTYPE> <!-- use module --> <html ng-app="exampleApp"> <head> <title>Angluar test</title> <Meta charset="utf-8"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> </head> <body ng-controller="defaultCtrl"> <div class="well"> <p><input class="form-control" ng-model="htmlData"></p> <!-- 显示危险数据,NG自动过滤html标签 --> <p>{{htmlData}}</p> <!-- 进行不安全绑定, 可以解析html,但是去除了JS等属性 --> <p ng-bind-html="htmlData"></p> <!-- 受信任的数据,当鼠标移到标签上,弹出JS对话框 --> <p ng-bind-html="trustData"></p> </div> <script type="text/javascript" src="js/angular.min.js"></script> <script type="text/javascript" src="js/angular-sanitize.min.js"></script> <!-- 引入指令文件 --> <script type="text/javascript"> // 使用指令 angular.module("exampleApp",["ngSanitize"]) .controller("defaultCtrl",$sce) { // 数据模型 $scope.htmlData = "<p>This is <b onmouSEOver=alert('aaa')>danger</b> data</p>"; $scope.trustData = "<p>This is <b onmouSEOver=alert('trust')>trust</b> data</p>"; $scope.trustData = $sce.trustAsHtml($scope.trustData); }) </script> </body> </html>

    四、使用AngularJS 表达式和指令
    1.将NG表达式转换为函数

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <div class="well">
            <p><input class="form-control" ng-model="expr"></p>
            <div>
                Result: <span eval-expression="expr"></span>
            </div>
        </div>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",$document) { $scope.price = "100.23"; }) .directive("evalExpression",function ($parse) { return function (scope,element,attrs) { scope.$watch(attrs["evalExpression"],function (newValue) { try { // 获取表单输入内容 var expressionFn = $parse(scope.expr); // 将函数生成内容 var result = expressionFn(scope); if (result == undefined) { result = "No result"; } } catch (err) { result = "Cannot evaluate expression"; } element.text(result); }) } }) </script>
    </body>
    </html>

    像上述例子那样,你无法指望用户会输入”price | currency”之类的数据,所以我们要提供本地数据

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <div class="well">
            <p><input class="form-control" ng-model="dataValue"></p>
            <div>
                Result: <span eval-expression amount="dataValue" tax="10"></span>
            </div>
        </div>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",$document) { $scope.dataValue = "100.23"; }) .directive("evalExpression",function ($parse) { var expressionFn = $parse("total | currency"); // console.log(expressionFn); return { scope : { amount : "=amount",tax : "=tax" },link : function (scope,attrs) { scope.$watch("amount",function (newValue) { var localData = { total : Number(newValue) + (Number(newValue) * (Number(scope.tax) / 100)) } element.text(expressionFn(scope,localData)); }) } } }) </script>
    </body>
    </html>

    2.配置内插
    我们在使用{{和}}来单向绑定内联数据,它可能与JS或者是其他的模板混淆,因此我们可以改变它
    将{{}}改为!!!!

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <h4>!!data!!</h4>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",[]) .config(function ($interpolateProvider) { $interpolateProvider.startSymbol("!!"); $interpolateProvider.endSymbol("!!"); }) .controller("defaultCtrl",$window) { // 数据模型 $scope.data = "Good!"; }) </script>
    </body>
    </html>

    3.编译内容
    $compile服务处理包含绑定与表达式的HTML片段,它将创建可利用作用域生成内容函数

    <!DOCTYPE>
    <!-- use module -->
    <html ng-app="exampleApp">
    <head>
        <title>Angluar test</title>
        <Meta charset="utf-8"/>
        <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
    </head>
    <body ng-controller="defaultCtrl">
        <div class="well">
            <span eval-expression></span>
        </div>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <!-- 引入指令文件 -->
    <script type="text/javascript"> // 使用指令 angular.module("exampleApp",$document) { // 数据模型 $scope.cities = ["BeiJing","ShangHai","HangZhou"]; }) .directive("evalExpression",function ($compile) { return function (scope,attrs) { var content = "<ul><li ng-repeat='city in cities'>{{city}}</li></ul>"; var listEle = angular.element(content); var complileFn = $compile(listEle); complileFn(scope); element.append(listEle); } }) </script>
    </body>
    </html>
    原文链接:https://www.f2er.com/angularjs/149369.html

    猜你在找的Angularjs相关文章