Thursday, February 6, 2014

Angularjs - number only input directives

app.js:
app.directive('numberOnly', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            ngModel: '='
        },
        link: function (scope) {          
            scope.$watch('ngModel', function(newValue,oldValue) {        
                var arr = String(newValue).split("");
                if (arr.length === 0) return;
                if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.' )) return;
                if (arr.length === 2 && newValue === '-.') return;
                if (isNaN(newValue)) {
                    scope.ngModel = oldValue;
                }
            });
        }
    };
});

app.controller('MainCtrl', function($scope) {
  $scope.name = 0;
});

html:
<body ng-controller="MainCtrl">
    <input type="text" ng-model="name" number-only/>
</body>


That's it and simple.
demo here

Wednesday, February 5, 2014

Angularjs ng-grid : rowItem.rowIndex not map to the index of data array after sorting. (with solution)

I found that the rowIndex will no longer map to the index of the data array if sorting is applied.
Lastly, I found a way to locate the index of data array even after sorting is applied by using rowMap and the syntax like this:
$scope.gridOptions.ngGrid.rowMap.indexOf(rowItem.rowIndex);

instead of just using rowItem.rowIndex.


however, this is not officially documented. 
So, beware that there is any changes in the future updates/patches of the ng-grid. 
updated on 05 Feb 2014

With further studies, I found that selectedItems may serves the same purpose only when the multiSelect equals to false. So, it won't work exactly the same if you require the grid with multiSelect:true.