我正在尝试在我的ionic应用程序中实现一个angular指令,以添加一个“X”按钮到文本字段中,当点击该按钮时会清除文本。该代码基于此存储库:https://github.com/amageed/angular-resetfield
我无法调用重置匿名函数...即重置日志语句不显示,但链接语句显示:
以下是HTML中的使用方法:
.directive('resetField', ['$compile', '$timeout', function($compile, $timeout) {
return {
require: 'ngModel',
scope: {},
link: function(scope, el, attrs, ctrl) {
console.log('linking ');
// limit to input element of specific types
var inputTypes = /text|search|tel|url|email|password/i;
if (el[0].nodeName === "INPUT") {
if (!inputTypes.test(attrs.type)) {
throw new Error("Invalid input type for resetField: " + attrs.type);
}
} else if (el[0].nodeName !== "TEXTAREA") {
throw new Error("resetField is limited to input and textarea elements");
}
// compiled reset icon template
var template = $compile('<i ng-show="enabled" ng-click="reset();" class="icon ion-close reset-field-icon"></i>')(scope);
el.addClass("reset-field");
el.after(template);
scope.reset = function() {
console.log('resetting');
ctrl.$setViewValue(null);
ctrl.$render();
$timeout(function() {
el[0].focus();
}, 0, false);
scope.enabled = false;
};
el.bind('input', function() {
scope.enabled = !ctrl.$isEmpty(el.val());
})
.bind('focus', function() {
$timeout(function() {
scope.enabled = !ctrl.$isEmpty(el.val());
scope.$apply();
}, 0, false);
})
.bind('blur', function() {
$timeout(function() {
scope.enabled = false;
scope.$apply();
}, 0, false);
});
}
};
}]);
以下是HTML中的使用方法:
<input type="text" placeholder="Search" ng-model="query" autocorrect="off" reset-field>