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>

  • 相关阅读:
    门面模式 Facade
    适配器模式 Adapter
    建造者模式 Builder Mode
    原型模式 ProtoType
    抽象工厂模式 Abstract Factory
    工厂方法模式 Factory Method
    简单工厂模式 SimpleFactory
    java设计模式之代理设计模式(Proxy)
    java工厂设计模式初步
    java中的接口概念
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4152344.html
Copyright © 2011-2022 走看看