How to Perform an Action on Key Press in Angular JS

Here’s a quick way to perform certain operations on key press in an input field while working with AngularJS. E.g. say you want to prevent non-digits from being accepted in an input field.

<input name='foo' id='foo' ng-model='foo' ng-keypress="isNumber($event)" />

Then in your controller, you can do something like:

$scope.isNumber = function (event) {
    var charCode = (event.which) ? event.which: event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        event.preventDefault();
        return false;
    }
    return true;
};

How to Scroll to Top of Page on Changing Location in AngularJS App

In this post I discuss a quick way of fixing a minor annoyance you may experience while developing apps with AngularJS. Specifically, you may notice that when your app navigates from one url to another, the scroll location remains the same, which could causes lots of usability issues. To fix this, in your Angular module’s run method, call anchorscroll() in a callback function to the $locationChangeSuccess event as follows:

 angular.module('myAngularApp')
.run(function($rootScope, Auth, $state, $anchorScroll){
    $rootScope.$on("$locationChangeSuccess", function(){
        $anchorScroll();
    });

References

Changing route doesn’t scroll to top in the new page. Stack Overflow. http://stackoverflow.com/questions/21055952/changing-route-doesnt-scroll-to-top-in-the-new-page.

How to Make Checkbox Checked by Default in AngularJS

Here’s a quick tip on how to set a checkbox as checked by default when developing an app with AngularJS. In your controller, suppose you’re storing the form in a field someCheckboxField under a form variable someForm. All you need to do is set the field to true

e.g.

$scope.someForm = {
    someCheckboxField: true
};

Then in the template, make sure the checkbox has ng-model set appropriately, e.g.

 <input type='checkbox' name='someCheckboxField' ng-model='someForm.someCheckboxField' />