我在一个文本框中有两个指令。一个是datetimepicker和focus指令。
DateTimePicker:
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require : '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
element.datetimepicker({
format: "yyyy-mm-dd hh:ii:ss",
autoclose: true,
todayBtn: true
}).on('setDate', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
焦点:
app.directive('focus',function($timeout) {
return {
restrict: 'A',
scope : {
trigger : '@focus'
},
link : function(scope, elem,attrs) {
var focusables = $(":focusable");
scope.$watch('trigger', function(value) {
if (value === "true") {
$timeout(function() {
elem[0].focus();
});
}
});
elem.bind('keydown', function(e) {
var code = e.keyCode || e.which;
if (code === 13) {
var current = focusables.index(this);
var next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
e.preventDefault();
}
});
}
};
});
这是我的文本框
<input datetimepicker ng-model='dob' focus/>
我收到以下错误
Error: [$compile:multidir] Multiple directives [focus, datepicker] asking for new/isolated scope on: <input datepicker="" ng-model="dob" focus="">
如何使这两个指令在文本框中协同工作?
答案 0 :(得分:0)
尽量不要手动为第一个指令提供隔离范围,因为你不需要它,所以使用scope:false
,它会起作用。
app.directive('datetimepicker', function() {
return {
restrict: 'A',
require : '?ngModel',
scope: false,
link: function(scope, element, attrs, ngModelCtrl) {
element.datetimepicker({
format: "yyyy-mm-dd hh:ii:ss",
autoclose: true,
todayBtn: true
}).on('setDate', function(e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
答案 1 :(得分:0)
您遇到的问题是至少有两个指令需要新的或隔离的范围。
据我所知,您的focus
指令实际上并不需要隔离范围,因为您可以使用focus
来实现attrs.trigger
。
尝试将focus
指令更改为:
app.directive('focus',function($timeout) {
return {
restrict: 'A',
link : function(scope, elem,attrs) {
var focusables = $(":focusable");
scope.$watch(attrs.trigger, function(value) {
if (value === "true") {
$timeout(function() {
elem[0].focus();
});
}
});
elem.bind('keydown', function(e) {
var code = e.keyCode || e.which;
if (code === 13) {
var current = focusables.index(this);
var next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
e.preventDefault();
}
});
}
};
});