angular directive ignore non-numeric input

HTML: <input production-qty type=”text” maxlength=”3″ ng-model=”qty1″> Directive: app.directive(‘productionQty’, function() { return { require: ‘ngModel’, link: function (scope, element, attr, ngModelCtrl) { function fromUser(text) { var transformedInput = text.replace(/[^0-9]/g, ”); console.log(transformedInput); if(transformedInput !== text) { ngModelCtrl.$setViewValue(transformedInput); ngModelCtrl.$render(); } return transformedInput; // or return Number(transformedInput) } ngModelCtrl.$parsers.push(fromUser); } }; }); Plunker See also filters on ng-model in … Read more

Detect unsaved changes and alert user using angularjs

Something like this should do it: <!doctype html> <html ng-app=”myApp”> <head> <script src=””></script> <script type=”text/javascript”> function Ctrl($scope) { var initial = {text: ‘initial value’}; $scope.myModel = angular.copy(initial); $scope.revert = function() { $scope.myModel = angular.copy(initial); $scope.myForm.$setPristine(); } } angular.module(“myApp”, []).directive(‘confirmOnExit’, function() { return { link: function($scope, elem, attrs) { window.onbeforeunload = function(){ if ($scope.myForm.$dirty) { return … Read more

Call a method of a controller from another controller using ‘scope’ in AngularJS

The best approach for you to communicate between the two controllers is to use events. Scope Documentation In this check out $on, $broadcast and $emit. In general use case the usage of angular.element(catapp).scope() was designed for use outside the angular controllers, like within jquery events. Ideally in your usage you would write an event in … Read more

How to Create simple drag and Drop in angularjs

I just posted this to my brand spanking new blog: Code here: Demo here: Here are the directives these rely on a UUID service which I’ve included below: var module = angular.module(“lvl.directives.dragdrop”, [‘’]); module.directive(‘lvlDraggable’, [‘$rootScope’, ‘uuid’, function($rootScope, uuid) { return { restrict: ‘A’, link: function(scope, el, attrs, controller) { console.log(“linking draggable element”); … Read more

Confirmation dialog on ng-click – AngularJS

If you don’t mind not using ng-click, it works OK. You can just rename it to something else and still read the attribute, while avoiding the click handler being triggered twice problem there is at the moment. I think the problem is terminal instructs other directives not to run. Data-binding with {{ }} is … Read more

Call a controller function from a directive without isolated scope in AngularJS

Since the directive is only calling a function (and not trying to set a value on a property), you can use $eval instead of $parse (with a non-isolated scope): scope.$apply(function() { scope.$eval(attrs.confirmAction); }); Or better, simply just use $apply, which will $eval()uate its argument against the scope: scope.$apply(attrs.confirmAction); Fiddle