Javascript 如果我想创建只与自定义元素匹配的指令&&;安替比妥
假设我想创建一个指令,该指令只与匹配的元素相匹配Javascript 如果我想创建只与自定义元素匹配的指令&&;安替比妥,javascript,angularjs,directive,Javascript,Angularjs,Directive,假设我想创建一个指令,该指令只与匹配的元素相匹配amInput[type=dropdown]我该怎么做 例如,我可以: .directive('amInput',function () { return { restrict: "E", scope: { data:'@' }, compile:function(tElement, tAttrs){
amInput[type=dropdown]
我该怎么做
例如,我可以:
.directive('amInput',function () {
return {
restrict: "E",
scope: {
data:'@'
},
compile:function(tElement, tAttrs){
if (tAttrs.type != 'dropdown') return;
return function link ($scope, element, attr, ctrl) {
var parseResult = parse($scope.data);
}
}
}
});
但是如果我为am input[type=checkbox]
.directive('amInput',function () {
return {
restrict: "E",
scope: {
data2:'@'
},
compile:function(tElement, tAttrs){
if (tAttrs.type != 'checkbox') return;
return function link ($scope, element, attr, ctrl) {
var parseResult = parse($scope.data2);
}
}
}
});
angular#$compile
抛出异常关于两个指令定义隔离范围
错误:[$compile:multidir]多个指令[amInput,amInput]请求在以下位置上创建新的/隔离的作用域:
指令名称应该是唯一的(只要它们匹配相同的限制)
在您的情况下,您可能应该将它们合并为一个
(作为参考,这可能会有所帮助:)好的,我最终得到的解决方案是通过
postlink
对指令进行区分。当prelink
适用于所有情况时,它们之间的情况类似:
directive('amInput',function () {
var template = {
'dropdown' :require('./dropdown.drv.html'),
'checkbox-group' :require('./checkbox-group.drv.html')
};
var postLinkPerType = {
'dropdown': require('./postLink-OneFromMany'),
'checkbox-group':require('./postLink-ManyFromMany')
};
return {
restrict: "E",
require: 'ngModel',
scope:{
selectAll:'='
//,...
},
transclude:true,
controller: function(scope, element, attr) {
/*for binding stuff that use by post links */
},
controllerAs:'inputCtrl',
bindToController:false,
template: function (element, attr) {
return template[attr.type];
},
compile: function (element, attr, ctrl, transcludeFn) {
return {
pre: function (scope, element, attr, ctrl, transcludeFn) {
/*******************************************/
/* some general/init code for all collection*/
/*******************************************/
/* init options list */
if( attr.data ){
/***********/
/* some code just if there is some attribute*/
/***********/
}
},
/*the little different code that make every directive in collection different*/
/*different by TYPE attribute*/
post: postLinkPerType[attr.type]
}
}
}
})如果只使用一个direcitve,检查类型并在此基础上返回链接函数可能会更容易,而不是在类型错误时仅返回您的想法是好的。我应该采纳它。但是,如果每个指令的作用域不同(如示例中所示),如果我正确理解了您的意思,那么它实际上不会有什么区别,可以在作用域中声明
data
和data2
,然后您只需使用所需的一个。您甚至可以在每个相应的链接函数中进行检查,以确保未定义data
或data2
。