首页 > 代码库 > [AngularJS] Hijacking Existing HTML Attributes with Angular Directives
[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="http://www.mamicode.com/" 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>
[AngularJS] Hijacking Existing HTML Attributes with Angular Directives
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。