Rectangle 27 16

After trying a bunch of things, this is seems not possible, as you would need to pass $event to get the target element, so separate directive seems to be the only way to go:

You cannot pass this because it refers to the scope, so you need to pass the event.

<input type="text" ng-enter="doBlur($event)">

Once you have the event, you can get the target from it.

$scope.doBlur = function($event){
    var target = $event.target;

    // do more here, like blur or other things
    target.blur();
}

But, you can only get pass event in a directive like ng-click ... kinda unsatisfactory. If we could pass $event outside directive, we could blur in that reusable way you requested.

I hate to say this, but it seems jQuery would be easier to use in this case

This solution worked with me only when I passed the event parameter as per this line of code: scope.$eval(attrs.ngEnter, {'event': event});. Thanks a lot.

Worked fine in Chrome, but in Firefox and Edge the focus was lost. To keep focus: target.focus()

angularjs - Blur an input field on keypress enter on Angular - Stack O...

angularjs blur
Rectangle 27 3

SoluableNonagon was very close to it. You just have to use the right argument. The directive declared the event parameter as event not $event. You could change the directive to use $event just as ngClick does (Or you keep it and use it as ng-enter="doSomething(event)".

angular.module("app", [])
  .controller('MainController', MainController)
  .directive('myEnter', myEnter);

function MainController() {
  var vm = this;
  vm.text = '';
  vm.enter = function($event) {
    $event.target.blur();
    vm.result = vm.text;
    vm.text = '';
  }
}

myEnter.$inject = ['$parse'];

function myEnter($parse) {
  return {
    restrict: 'A',
    compile: function($element, attr) {
      var fn = $parse(attr.myEnter, null, true);
      return function(scope, element) {
        element.on("keydown keypress", function(event) {
          if (event.which === 13) {
            
            // This will pass event where the expression used $event
            fn(scope, { $event: event });
            scope.$apply();
            event.preventDefault();
          }
        });
      };
    }
  };
}
<script src="https://code.angularjs.org/1.4.8/angular.js"></script>

<div ng-app="app" ng-controller="MainController as view">
  <input my-enter="view.enter($event)" ng-model="view.text">
  <div ng-bind="view.result"></div>
</div>

angularjs - Blur an input field on keypress enter on Angular - Stack O...

angularjs blur
Rectangle 27 1

You cannot directly call the function specifically on Enter key press, use a function to check if the Enter key is pressed and then call your function.

<input type="text" ng-keypress="myFunc(e)" />
<!--               ^^^^^^^^^^^^^^^^^^^^^^^ -->
<i class=buttonone"></i>
$scope.myFunc = function (event) {
    if (event.keyCode === 13) {
        console.log('Enter key pressed');

        $scope.tool.disc(); // Call your function here
    }
};

Why would you listen to keypress on an anchor ? You just can't "type in" an anchor.

Thanks alot for your kind help! I have several links, is it possible to add it to a div around them (or some other solution) and when pressing left / right arrow keys, navigate which one is in focus? Then when I press enter on one of them, it should trigger its function? Sorry if its advanced and to much to ask but you're a lifesaver if you make it happen!

javascript - How to keypress in AngularJS - Stack Overflow

javascript angularjs angularjs-directive angularjs-ng-repeat keypress
Rectangle 27 5

You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/ which provide details event handle callback function for detecting keydown,keyup,keypress (also Enter key, backspace key, alter key ,control key)

<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>

html - How can I detect keydown or keypress event in angular.js? - Sta...

html twitter-bootstrap angularjs angularjs-directive
Rectangle 27 2

We can write the directive to listen to the keypress event. But for some old browsers, this event is not triggered. Thats why i created a directive in such a way that there's no dependency on browser specific events limitation. I created an angular directive to limit the number of text in the input box.

'use strict';
angular.module("appName")
.directive("limitTo", [function() {
return {
restrict: "A",
require: "ngModel",
link: function(scope, elem, attrs, ctrl) {
    var limit = parseInt(attrs.limitTo);
    ctrl.$parsers.push(function (value) {
        if (value.length > limit){
            value = value.substr(0, limit);
            ctrl.$setViewValue(value);
            ctrl.$render();
        }
        return value;
    });
 }
}}]);
<input limit-to="3" ng-model="test"/>

How can you limit the value from input using AngularJS? - Stack Overfl...

angularjs angularjs-directive
Rectangle 27 2

We can write the directive to listen to the keypress event. But for some old browsers, this event is not triggered. Thats why i created a directive in such a way that there's no dependency on browser specific events limitation. I created an angular directive to limit the number of text in the input box.

'use strict';
angular.module("appName")
.directive("limitTo", [function() {
return {
restrict: "A",
require: "ngModel",
link: function(scope, elem, attrs, ctrl) {
    var limit = parseInt(attrs.limitTo);
    ctrl.$parsers.push(function (value) {
        if (value.length > limit){
            value = value.substr(0, limit);
            ctrl.$setViewValue(value);
            ctrl.$render();
        }
        return value;
    });
 }
}}]);
<input limit-to="3" ng-model="test"/>

How can you limit the value from input using AngularJS? - Stack Overfl...

angularjs angularjs-directive
Rectangle 27 0

Yea that would work but I stated in my answer that it wouldn't work for a stable build of AngularJS. ng-model-options is only available in their beta build (v1.3+). I'm using v1.2.

angular ngmodel - Update AngularJS ng-model only on keypress enter? - ...

angularjs angular-ngmodel
Rectangle 27 0

This is the old solution. Now that Angular v1.3 is stable, use accepte...

This takes into account blur and pressing enter. It's a bit hacky and I think there are new ways to do this in the beta version of Angular. Guess this will do until AngularJS v1.3 is more stable.

angular ngmodel - Update AngularJS ng-model only on keypress enter? - ...

angularjs angular-ngmodel
Rectangle 27 0

Since one of the other answers addresses the ng-keypress, I'll offer up the fact you don't need to use the ng-keypress event but can just watch the variable instead which negates the need for enter:

app.controller('MainCtrl', function($scope) {
  $scope.taskList = [];

 $scope.$watch('newTask', function(newVal){
     if (newVal=="newTask") {
       $scope.taskList.push("Task " + $scope.taskList.length);
       $scope.newTask = null;
     }
 });
});



 <body ng-controller="MainCtrl">
    <div class="add-task">
  <input type="text" placeholder="Type then press enter to create task" ng-model="newTask" />
</div>

{{taskList.length}}
<div class="task-list" >
  <a class="task" ng-repeat="task in taskList" ><span class="text">{{ task }}&nbsp;</span></a>
</div>
  </body>

This seems like the nicest method of achieving, but the Plunker you've linked to doesn't seem to work?

If you type in newTask (exactly) into the textbox it works. In general $scope.$watch runs everytime the variable changes so you can avoid the function on the keypress event.

angular ui - Bind dynamic element creation to keypress with AngularJS ...

angularjs angular-ui angularjs-model
Rectangle 27 0

You can do that to enable search in ng-keypress enter for input text and in ng-click for the icon:

<input type="text" ng-model="searchText" ng-keypress="keyEnter(this,$event)" />
<button ng-click="check(searchText)">Check!</button>

in the controller
$scope.search = function (searchText) {
        console.log(searchText);
    }
    $scope.keyEnter = function (serachText,$event) {
        var keyCode = $event.which || $event.keyCode;
        if (keyCode === 13) {//KeyCode for Enter key
           console.log(searchText);
        }
    }

javascript - Ng-model does not update controller value - Stack Overflo...

javascript angularjs data-binding angular-ngmodel
Rectangle 27 0

You can do that to enable search in ng-keypress enter for input text and in ng-click for the icon:

<input type="text" ng-model="searchText" ng-keypress="keyEnter(this,$event)" />
<button ng-click="check(searchText)">Check!</button>

in the controller
$scope.search = function (searchText) {
        console.log(searchText);
    }
    $scope.keyEnter = function (serachText,$event) {
        var keyCode = $event.which || $event.keyCode;
        if (keyCode === 13) {//KeyCode for Enter key
           console.log(searchText);
        }
    }

javascript - Ng-model does not update controller value - Stack Overflo...

javascript angularjs data-binding angular-ngmodel
Rectangle 27 0

var app = angular.module('contra', []);
app.directive('code', function () {
    function codeState() {
        this.currentState = 0;
        this.keys = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65];
        this.keyPressed = function (key) {
            if (this.keys[this.currentState] == key) {
                this.currentState++;
                if (this.currentState == this.keys.length) {
                    this.currentState = 0;
                    return true;
                }
            } else {
                this.currentState = 0;
            }
            return false;
        };
    };
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            var cs = new codeState();
            scope.isValid = "NO";
            element.bind("keydown", function (event) {
                scope.$apply(function () {
                    if (cs.keyPressed(event.which)) {
                        scope.isValid = "YES";
                        console.log("CODE ENTERED");
                    } else {
                        scope.isValid = "NO";
                    }
                });
            });
        }
    }
});

What's different about this is it's a directive so if you attach this on the body, it'll apply to the whole page. This also allows for entering the code multiple times.

Does the plnkr work? I added this to my app directive, it binds to it, but I don't see how to fire it. When I try the plnkr, it just reports NO to the example. Am I doing something wrong?

How to watch for a keypress combination in Angularjs? - Stack Overflow

angularjs keypress
Rectangle 27 0

You can do that to enable search in ng-keypress enter for input text and in ng-click for the icon:

<input type="text" ng-model="searchText" ng-keypress="keyEnter(this,$event)" />
<button ng-click="check(searchText)">Check!</button>

in the controller
$scope.search = function (searchText) {
        console.log(searchText);
    }
    $scope.keyEnter = function (serachText,$event) {
        var keyCode = $event.which || $event.keyCode;
        if (keyCode === 13) {//KeyCode for Enter key
           console.log(searchText);
        }
    }

javascript - Ng-model does not update controller value - Stack Overflo...

javascript angularjs data-binding angular-ngmodel
Rectangle 27 0

I get what you mean by having it be a separate resource. To me, it seems to go against thinking in Angular, as events really should be "controlled." If you want to have all keypress (or click) events centralized, maybe a switch/case is in order:

$scope.keypressHandler = function () {
switch ($event.keyCode)
{
case 13:
$scope.someEnterKeyFunction();
break;
default:
$scope.someDefaultFunction();
break;
}
}

I'm not sure I understand how using switch comes into the solution. I'm trying to trigger an event in a factory, rather than through a controller, and the controllers listen to factory events already. Maybe I am just not understanding your complete solution.

I misread a little bit, but I think I'd still go for having the handling of the keypress events in the controller, and then farm out the actual logic to the factory function(s). My reply was just in response to your initial line that you'd "prefer not to litter my code with a keypress here and a keypress there." A combination of switch/case in the controller for each potential keypress and then each of those calling their respective factory function, seems to at least structurally fit the bill.

gotcha, but I've got more than one controller that will be responding to keypress events. Hence the reason I'd like to keep all the keypress events together in one place, have the keypress affect the respective factories, and have the controllers listen for those factory events.

angularjs - Angular.js keypress events and factories - Stack Overflow

angularjs keyboard-shortcuts
Rectangle 27 0

.directive('numbersCommaOnly', function(){
   return {
     require: 'ngModel',
     link: function (scope, element, attrs, ngModel) {

        element.on('keydown', function(event) {                  
            // Allow: backspace, delete, tab, escape, enter and .
            var array2 = [46, 8, 9, 27, 13, 110, 190]
            if (array2.indexOf(event.which) !== -1 ||
                 // Allow: Ctrl+A
                (event.which == 65 && event.ctrlKey === true) ||
                 // Allow: Ctrl+C
                (event.which == 67 && event.ctrlKey === true) ||
                 // Allow: Ctrl+X
                (event.which == 88 && event.ctrlKey === true) ||
                 // Allow: home, end, left, right
                (event.which >= 35 && event.which <= 39)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
                event.preventDefault();
            }
         });

     }
   };
})

javascript - angularjs: allows only numbers to be typed into a text bo...

javascript ruby-on-rails angularjs numeric
Rectangle 27 0

After trying a bunch of things, this is seems not possible, as you would need to pass $event to get the target element, so separate directive seems to be the only way to go:

You cannot pass this because it refers to the scope, so you need to pass the event.

<input type="text" ng-enter="doBlur($event)">

Once you have the event, you can get the target from it.

$scope.doBlur = function($event){
    var target = $event.target;

    // do more here, like blur or other things
    target.blur();
}

But, you can only get pass event in a directive like ng-click ... kinda unsatisfactory. If we could pass $event outside directive, we could blur in that reusable way you requested.

I hate to say this, but it seems jQuery would be easier to use in this case

angularjs - Blur an input field on keypress enter on Angular - Stack O...

angularjs blur
Rectangle 27 0

You first problem with you code is that you are binding it on keypress. That mean $("#txthour").val() will not be updated before your event.

You need to know which character the user has pressed. There is a function for that : String.fromCharCode();.

To get the current character, you can use that :

var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);

then you need to check if it is a number.

if(!isNaN(currentChar))
var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition

Parse the new value and check if it's lower or equal to 12. If all these condition match, return true.

To allow the press of the enter key, you need to check if the keycode is 13 :

function isNumberKey(e) {
    if(e.keyCode === 13) return true;
    var currentChar = parseInt(String.fromCharCode(e.keyCode), 10);
    if(!isNaN(currentChar)){
        var nextValue = $("#txthour").val() + currentChar; //It's a string concatenation, not an addition

        if(parseInt(nextValue, 10) <= 12) return true;
    }

    return false;
}

unfortunately its not working in firefox...what can i do???

@ShitalKadam use e.which instead of keyCode. Also need to check if it's the backspace key : jsfiddle.net/6X9Yq/1

javascript - Don't allow the user to enter numbers greater than 12 - S...

javascript jquery
Rectangle 27 0

Use ng-model options. Using a blur hack is tricky, because a blur may not be a change.

<input type="text" ng-model="a.b" ng-change="callScriptThenServer()" ng-model-options={updateOn: 'blur'}"/>

angularjs - Configure Angular to re-evaluate on blur instead of keypre...

angularjs
Rectangle 27 0

.directive('numbersCommaOnly', function(){
   return {
     require: 'ngModel',
     link: function (scope, element, attrs, ngModel) {

        element.on('keydown', function(event) {                  
            // Allow: backspace, delete, tab, escape, enter and .
            var array2 = [46, 8, 9, 27, 13, 110, 190]
            if (array2.indexOf(event.which) !== -1 ||
                 // Allow: Ctrl+A
                (event.which == 65 && event.ctrlKey === true) ||
                 // Allow: Ctrl+C
                (event.which == 67 && event.ctrlKey === true) ||
                 // Allow: Ctrl+X
                (event.which == 88 && event.ctrlKey === true) ||
                 // Allow: home, end, left, right
                (event.which >= 35 && event.which <= 39)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((event.shiftKey || (event.which < 48 || event.which > 57)) && (event.which < 96 || event.which > 105)) {
                event.preventDefault();
            }
         });

     }
   };
})

javascript - angularjs: allows only numbers to be typed into a text bo...

javascript ruby-on-rails angularjs numeric
Rectangle 27 0

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
Informe your name:<input type="text" ng-model="pergunta" ng-keypress="pressionou_enter($event)" ></input> 
<button ng-click="chamar()">submit</button>
<h1>{{resposta}}</h1> 
</div>
<script>
var app = angular.module('myApp', []);
//create a service mitsuplik
app.service('mitsuplik', function() {
    this.myFunc = function (parametro) {
        var tmp = ""; 
        for (var x=0;x<parametro.length;x++)
            {
            tmp = parametro.substring(x,x+1) + tmp;
            } 
        return tmp;
    }
});
//Calling our service
app.controller('myCtrl', function($scope, mitsuplik) { 
  $scope.chamar = function() { 
        $scope.resposta = mitsuplik.myFunc($scope.pergunta); 
    };
  //if mitsuplik press [ENTER], execute too
  $scope.pressionou_enter = function(keyEvent) {
             if (keyEvent.which === 13) 
                { 
                $scope.chamar();
                }

    }
});
</script>
</body>
</html>

How to use a keypress event in AngularJS? - Stack Overflow

angularjs angularjs-directive angular-ui