[AngularJS] Hijacking Existing HTML Attributes with Angular Directives

weixin_34198583發表於2014-12-09

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>

相關文章