Reputation: 87
I am trying to edit a field and convert label into text field on click of a button and change it back to label on keypress event (ng-keypress).
I am changing the ng-show variable through controller but it is not working.
HTML:
<div ng-app>
<div ng-controller="showCrtl">
<form>
<label ng-hide="editMode" >{{field}}</label>
<input ng-show="editMode" ng-keypress="changemode($event) " ng-model="field" >
<span class="pull-right" >
<button ng-click="editMode=true" class="btn-lg btn-warning" >edit </button> </span>
</form>
</div>
</div>
JS:
function showCrtl($scope){
$scope.field="Chanel";
$scope.changemode=function(event){
if(event.charCode==13){
$scope.editMode = false;
}
}
}
My updated JS-Fiddle link: http://jsfiddle.net/8Yz7S/281/
Upvotes: 0
Views: 1584
Reputation: 2979
The reason its not working for you is that, you are not preventing the default behavior of Enter
key. So After changemode
function is executed and editmode
is set to false
, click event of Edit button is also getting executed, setting editmode
back to true
.
All you need to do is call event.preventDefault();
as shown below:
function showCrtl($scope){
$scope.field="Chanel";
$scope.changemode=function(event){
if(event.charCode==13){
$scope.editMode = false;
event.preventDefault(); // <<<<<<<
}
}
}
To verify this behavior you can check this fiddle: http://jsfiddle.net/vnathalye/8Yz7S/301/
Try it after commenting the line event.preventDefault();
and check the console.
Upvotes: 1
Reputation: 641
Can you try the below solution.
<input ng-show="editMode" ng-keypress="changemode($event) " >
Added interval to update the view
function showCrtl($scope, $timeout){
$scope.changemode=function(event){
if(event.charCode==13){
$timeout(function() {
$scope.editMode = false;
}, 500);
}
}
}
http://jsfiddle.net/gsjsfiddle/hcu5mkhm/3/
Upvotes: 1
Reputation: 331
You want to obfuscate as much logic as possible from the view. So as he suggested, use
<input ng-show="editMode" ng-keypress="changemode($event)">
Then, do all your logic inside the changemode() function:
$scope.changemode = function(evt) {
$timeout(function() {$scope.editMode = false;},100);
}
http://jsfiddle.net/8Yz7S/293/
Upvotes: 0
Reputation: 222722
Use ng-blur instead of ng-keypress,
<input ng-show="editMode" ng-blur="changemode() " >
EDIT:
Use the following directive to handle the enter key event,
app.directive('ngEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.ngEnter);
});
event.preventDefault();
}
});
};
});
Upvotes: 2