如果你只是想阻止用户输入逗号,你可以在没有 jQuery 的情况下做到这一点:
$html.on('keydown', 'li', function (e) {
if (e.keyCode === 188) {
return false;
}
});
还有(据我所知,在有限的上下文中)没有理由使用 $compile。您应该能够只使用模板:
http://jsfiddle.net/VM285/
myApp.directive('mydirective', function () {
return {
restrict: 'E',
replace: true,
scope: {
list: '='
},
link: function (scope, element, attrs) {
element.bind('keydown', function (e) {
if (e.keyCode === 188) {
e.preventDefault();
return false;
}
});
},
template: '<div><ul ng-model="list"><li ng-repeat="item in list"><input ng-model="item.Name" type="text" /></li></ul></div>'
}
});
更进一步,您可以完全无需 DOM 操作来完成此操作:
http://jsfiddle.net/VM285/1/
myApp.directive('mydirective', function () {
return {
restrict: 'E',
replace: true,
scope: {
list: '='
},
link: function (scope, element, attrs) {
scope.checkForComma = function(item) {
if (item.Name.indexOf(',') > -1) {
item.Name = item.Name.replace(/,/g, '');
}
};
},
template: '<div><ul ng-model="list"><li ng-repeat="item in list"><input ng-model="item.Name" type="text" ng-change="checkForComma(item)" /></li></ul></div>'
}
});