Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RangeError when binding input to array.length

Tags:

angularjs

<div ng-app="">
<div ng-controller="MyCtrl">
    <input required type="number" ng-model="teams.length" min="1" max="9">    
    <span>pressing backspace to remove the number causes an exception</span>

    <div ng-repeat="team in teams track by $index">
        team {{$index+1}}
    </div>
</div>

    function MyCtrl($scope) {
    $scope.teams = [{}];
}

pressing backspace in the input causes the exception:

RangeError: Invalid array length
at setter (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:9982:12)
at token.fn.extend.assign (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:9429:18)
at $setViewValue (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:16390:7)
at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:15654:14
at Scope.$eval (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:11576:28)
at Scope.$apply (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:11676:23)
at HTMLInputElement.listener (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:15653:13)
at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:2562:10
at Array.forEach (native)
at forEach (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:300:11) 

What I'd like to happen instead is for the input to fail authentication (ng-invalid). I'm running angular 1.2.16

JSFiddle

like image 539
Soroush Hakami Avatar asked Apr 23 '14 07:04

Soroush Hakami


1 Answers

Do not bind directly on teams.length; rather create a new variable, say length, and bind to it. Then $watch it and apply the changes to teams.length, if appropriate. Make the input ng-required="true".:

<input ng-required="true" type="number" ng-model="length" min="1" max="9" />

And:

function MyCtrl($scope) {
    $scope.teams = [{}];
    $scope.length = $scope.teams.length;

    $scope.$watch("length", function(newlength) {
        if( newlength ) {
            $scope.teams.length = newlength;
        }
    });
}

Fiddle: http://jsfiddle.net/6pcVN/

like image 196
Nikos Paraskevopoulos Avatar answered Oct 01 '22 21:10

Nikos Paraskevopoulos