One issue I encountered involved an editable text field directive in Angular, which is structured like this:
myApp.directive('editable', function () {
return {
restrict: 'E',
scope: {
model: '=',
placeholder: '@'
},
replace: false,
template: '<span>' +
'<input type="text" class="form-control" placeholder="Press enter to submit changes" ng-model="model" style="width: 100%; font-size: 18px" ng-show="edit" ng-enter="edit=false"></input>' +
'<span ng-show="!edit">{{model || placeholder}} <i class="fa fa-pencil" style="font-size:14px;"></i></span>' +
'</span>',
link: function (scope, element, attrs) {
scope.edit = false;
element.bind('click', function () {
scope.$apply(scope.edit = true);
element.find('input').focus();
});
}
};
});
myApp.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind('keypress', function (e) {
if (e.charCode === 13 || e.keyCode === 13) {
scope.$apply(attrs.ngEnter);
}
});
};
});
The current implementation relies on the ng-enter
directive triggering actions upon pressing the enter key.
My goal now is for the functionality to also be triggered when clicking away from the element. I attempted to include additional code for this purpose, however, it did not yield the desired outcome:
myApp.directive('ngEnter', function () {
return function (scope, element, attrs) {
element.bind('keypress', function (e) {
if (e.charCode === 13 || e.keyCode === 13) {
scope.$apply(attrs.ngEnter);
}
});
element.bind('keypress', function (m) {
if (m.charCode === 1 || m.keyCode === 1) {
scope.$apply(attrs.ngEnter);
}
});
};
});
I'm currently seeking insights on why this modification did not work as intended.