Skip to content Skip to sidebar Skip to footer

Ng-model To Async Xhr Get/set Field On My Server

I'm using Angular to create a preferences page. Basically I have this field in a mysql table on my server, I want to ng-model my textbox to an async xhr request that sets it, and g

Solution 1:

Here is a shot in the dark of what I believe you are after. First, ng-pattern will not prevent typing, only trigger validation. Instead, start out by using input[number]. I'm also guessing you wish to see the manual value you set in your <input />, and not the keyed entry. For this, fire off $event.preventDefault(), bound to ng-keydown. Here is a complete working sample I wrapped in a decorator directive called async. Observe the following...

<inputtype="number"async ng-keydown="sync($event)" ng-model="model" />

.directive('async', ['myService', function(myService) {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ngModel) {

            scope.sync = function($event) {
                $event.preventDefault();

                myService.getValue().then(function(response) {
                    myService.setValue(response).then(function(final) { 
                        ngModel.$setViewValue(final)
                        ngModel.$render();
                    });
                });
            }
        }
    }
}]);

Where myService is a mocked service leveraging $q and $timeoutto emulate asynchronous behavior...

.factory('myService', ['$q', '$timeout', function($q, $timeout) {

    functiongetValue () {
        var deferred = $q.defer();

        $timeout(function () {
            deferred.resolve(123);
        }, 250);

        return deferred.promise;
    }

    functionsetValue(value) {
        var deferred = $q.defer();

        $timeout(function () {
            deferred.resolve(value);
        }, 250);

        return deferred.promise;
    }

    return {
        getValue: getValue,
        setValue: setValue
    }
}]);

Where 123 - a sample value - is asynchronously daisy chained through the getValue and setValue functions. The result from getValue is also passed as a parameter to setValue in case further manipulation is needed before finally calling ngModel.$setViewValue and ngModel.$render(). Additionally, your objective is to likely leverage a request in getValue(). When getting to that point, simply inject a service such as $http and model accordingly...

function getValue () {
    return $http.get('/endpoint');
}

JSFiddle Link - working demo - type 1 => 500ms => 123


If my assumption was wrong where you wished to prevent the keyed value initially, you can alternatively bind to ng-change and remove $event.preventDefault. If you chose this, you'll see your initial typed value, which will then change (get/set) as expected.

Post a Comment for "Ng-model To Async Xhr Get/set Field On My Server"