[英]AngularJS Directive for specific tag name
如何在AngularJS中強制指令的特定標記?
例如,我想創建一個僅應用於<img>
標簽的指令。 如果用戶將此指令放在<div>
,我不希望該指令處於活動狀態。 我怎樣才能做到這一點?
你有2個選擇。
#1使用您現有的指令,添加幾行
碼:
link: function(scope,element,attr) {
if (element[0].tagName== 'IMG') {
//do your stuff
} else {
// do nothing or something else
}
}
#2將你的指令限制為一個元素(如Fizer Khan的回答所示)。
.directive('myIMG', function() {
return {
restrict: 'E',
templateUrl: 'img.html',//essentially has <img src=''>
template: "<img src='scope.path'>",//build out your image tag here which will replace the HTML the directive is on
transclude: true,
scope: {
path: '='
},
link: function(scope, element, attr) {
}
};
});
HTML
<myIMG path=''></myIMG>
我個人最喜歡選項2。 但我知道這可能更令人生畏,並經常引入其他意想不到的事情。
盡管很久以前就已經提出了這個問題,但沒有答案可以對所需的元素本身進行指導。 所以這是另一種定義Angular指令的可能方法,該指令將自身限制為IMG
標記
appModule
.directive("img", function() {
restrict: "E",
link: function(scope, element, attributes) {
if (!element.hasClass("something") && !attributes.something)
{
// just a normal image
return;
}
// do your stuff
}
});
此代碼定義了IMG
元素的指令,但在初始化時,它會檢查是否在其上定義了特定的CSS類和/或HTML屬性。 如果沒有,則優雅地退出,因為此圖像不應該被定向 。 但如果其中任何一個被定義,它就會成功。
以下可能是最好的Angular方法。 IT由兩個指令組成。 一個在img
元素上,另一個是屬性/類指令,需要img
指令。
appModule
.directive("img", function() {
restrict: "E",
controller: function imgController() {
// does nothing really
}
})
.directive("imgSpecific", function() {
restrict: "AC",
require: "img",
link: function() {
// do your stuff
}
});
因此第二個指令實際上需要一個img
指令,該指令限制同一元素上的圖像元素,如果存在,則該指令實際上將運行,否則它將產生運行時異常,因為它的要求不符合要求。
通過這種方式,兩個指令都將非常簡單,沒有任何特定的代碼來檢查指令實際執行的某些條件。 所有這些檢查都已經在Angular代碼中完成,我們的指令(特別是第二個/子代)只會在兩個都存在的情況下對圖像元素執行。
您可以在指令中將restrict
屬性設置為E
restrict: 'E'
標簽名稱始終是directive
名稱。
例
angular.module('myapp', [])
.directive('myTag', function() {
return {
restrict: 'E',
templateUrl: 'my-tag.html',
scope: {
},
link: function(scope, element, attr) {
}
};
});
只有使用此指令的方法是
<my-tag></mytag>
我建議您支持這兩種方法,因為Angular不限制元素標記名稱。 它似乎歸結為你想如何處理你的設計中的用戶錯誤。 用戶應該只在img元素上使用你的指令,那么當他們不遵循你的意圖時你想做什么? 如果你想優雅地處理錯誤並繼續,然后為他們插入一個img並繼續。
http://plnkr.co/edit/RCS8uZgPFx2VgxQv73A4?p=preview
<html>
<head>
<script data-require="angular.js@*" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<img src="http://www.w3.org/html/logo/img/badge-samples.png" img-test>
<div data-src="http://www.w3.org/html/logo/img/badge-samples.png" img-test></div>
<script>
var app=angular.module("app",[]);
app.directive("imgTest",function(){
var link=function(scope,elem,attrs){
var img;
if(elem.tagName !="IMG"){
img=document.createElement("img");
img.setAttribute("src",attrs.src);
elem.append(img);
}
};
return{
"link" : link
}
});
angular.bootstrap(document,["app"]);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.