有没有办法编写一个只适用于特定元素+属性+属性值的指令?
我的第一个目的是为了模块化和维护目的而有单独的指令,但是我担心因为我从Angular收到错误而不可能告诉我有多个指令匹配元素
所以我的场景如下:我想编写自己的输入元素,例如
<input type="time-picker">
<input type="date-picker">
所以我做了
app.directive('input', function () {
return {
restrict: 'E',
templateUrl: function ($element, $attrs) {
if ($attrs.type === 'date-picker' || $attrs.type === 'time-picker') {
return $attrs.type + '.html';
}
},
controller: function ($scope, $element, $attrs) {
if ($attrs.type === 'date-picker') {
console.log('date-picker');
}
else if($attrs.type === 'time-picker') {
console.log('time-picker');
}
}
}
});
只要页面中没有其他输入元素,这就可以正常工作。
如果我把
<input type="time-picker">
<input type="date-picker">
它工作正常。现在,如果我添加
<input type="text">
整个页面都挂了。
请看我的小提琴:http://jsfiddle.net/pWc3K/8/
答案 0 :(得分:1)
如果您将html更改为:
<input type="text" time-picker> <input type="text" date-picker>
然后你可以根据这些属性连接指令:
app.directive('timePicker', function(){
return {
restrict: 'A',
...
}
});
app.directive('datePicker', function(){
return {
restrict: 'A',
...
}
});
将时间选择器/日期选择器放在元素的输入类型中并不是真正有效。如果您阅读directives的角度文档,您将找到可以关联的不同内容的完整列表。这四个是:
E - Element name: <my-directive></my-directive>
A - Attribute: <div my-directive="exp"> </div>
C - Class: <div class="my-directive: exp;"></div>
M - Comment: <!-- directive: my-directive exp -->
答案 1 :(得分:0)
尝试并理解在AngularJs中,创建的自定义指令可能具有以下限制:
restrict选项通常设置为:
'A' - 仅匹配属性名称
'E' - 仅匹配元素名称
'C' - 仅匹配班级名称
'M' - 只有评论
这些限制可以根据需要组合使用: 例如: 'AEC' - 匹配属性或元素或类名