Angular JS Text Field Input Change - Watch

1.2k views Asked by At

I have a list of text fields with an empty text field at the end, bound to an array. I need to detect text entry on the empty text field so when a user starts typing a value, I add another empty element to array so the user always has another field ready to work with.

Should I use $watch or ng-change to see the change go down and add the element accordingly? I know $watch is always firing so it seems like that may be a bad option.

    <div ng-repeat="variation in productEditorModel.ColorVariations">
                                                <div class="form-inline">
                                                    <input type="text" id="txtVariationName" placeholder="Name" name="variationName" ng-model="variation.VariationName" required class="form-control">

                                                    </div>
                                            </div>
3

There are 3 answers

0
ivkremer On

Considering performance aspect, you should better use ng-change because it will work as you've added change listener on the input like $('input').change(...) just as you mentioned.

Considering UX and functionality aspects it is better and easier to simply use $scope.$watch('model', ...) in controller.

But still I suppose it depends on how many inputs you will have. I think there is no really big difference with even 100+ inputs because you just comparing strings, I don't think that user will struggle with delays as he types.

2
zszep On

Why don't you bind the array to an ng-repeat of input elements? This way the binding will work automatically.

0
Mike Anderson On

thanks for the input, ng-change worked best.

    ng-change="update(variation,$index);"

    $scope.update = function (variation, index) {
        if (!angular.isUndefined(variation.VariationName)) {
            if (variation.VariationName.length > 0) {
                $scope.addVariation(variation.VariationTypeId);
            } else {
                $scope.productEditorModel.ColorVariations.splice(index, 1);
                $scope.removeVariation(index, variation.VariationTypeId);
            }
        } else {
            $scope.removeVariation(index, variation.VariationTypeId);
        }
    }