zoukankan      html  css  js  c++  java
  • [AngularJS] Hijacking Existing HTML Attributes with Angular Directives

    Angular overrides quite a few existing HTML elements and attributes. This can be a useful technique in our own applications. We will build a directive that adds additional functionality to the src property of an <img>.

    Javascript:

    /**
     * Created by Answer1215 on 12/8/2014.
     */
    angular.module('app', []).directive('src', function () {
        var URL_RE = /^http://[^/]*/;
        var HTTP_RE = /^(http|https):///;
    
        return function (scope, element, attrs) {
            var context = {url: attrs.src.match(URL_RE)[0]};
            context.domain = context.url.replace(HTTP_RE, '');
            /*
            * Object {url: "http://fursealworld.com", domain: "fursealworld.com"} app.js:11
             Object {url: "http://resources.news.com.au", domain: "resources.news.com.au"} app.js:11
             Object {url: "http://www.hdwallpaperscool.com", domain: "www.hdwallpaperscool.com"}
            * */
            var templateFn = _.template('<a href="<%= url %>" target="_blank">Photo courtesy of <%= domain %></a>');
            element.css({border: "2px solid grey"});
            element.after(templateFn(context));
        };
    });

    HTML:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Hijacking HTML Attributes</title>
        <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.css">
        <link rel="stylesheet" href="./main.css">
    </head>
    <body>
    
    
    <div class="container-fluid" ng-app="app">
        <div class="row">
            <div class="col-xs-4">
                <img src="http://fursealworld.com/wp-content/uploads/2013/03/1280BabyHarpSeal11.jpg"/>
            </div>
            <div class="col-xs-4">
                <img src="http://resources.news.com.au/files/2012/01/13/1226243/386315-harp-seal-1.jpg"/>
            </div>
            <div class="col-xs-4">
                <img src="http://www.hdwallpaperscool.com/wp-content/uploads/2014/10/baby-seal-widescreen-wallpaper-for-background-free.jpg"/>
            </div>
        </div>
    </div>
    
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.3/angular.js"></script>
    <script src="app.js"></script>
    </body>
    </html>

  • 相关阅读:
    内网穿透(Frp)-拯救没有公网IP的你
    用Windows远程桌面连接树莓派的方法
    TensorFlow 1.9开始支持树莓派
    树莓派制作遥控小车-新手教程
    Layui 一个页面包含多个table时不展示分页条
    MVC 通过@符号把数据赋值给jQuery对象
    jQuery 批量为表单元素赋值
    layui分页组件,一直在调用方法的解决办法
    layui 表格复选框不居中解决办法
    JQuery 解决遮罩层下内容可以滚动问题
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4152344.html
Copyright © 2011-2022 走看看