有没有办法编写仅适用于特定元素+属性+属性值的指令?
我的第一个意图是出于模块化和维护目的而拥有单独的指令,但恐怕这是不可能的,因为我从 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">
整个页面挂起。
在这里查看我的 fiddle :http://jsfiddle.net/pWc3K/8/
最佳答案
如果你将 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 的 Angular 文档您会发现可以关联的不同事物的完整列表。这四个是:
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 -->
关于javascript - Angular 指令限制的粒度更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16796450/