NG-模型异步我的服务器上XHR获取/设置场 [英] ng-model to async xhr get/set field on my server

查看:128
本文介绍了NG-模型异步我的服务器上XHR获取/设置场的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的角度来创建一个preferences页。

I'm using angular to create a preferences page.

基本上我已经在我的服务器上一个MySQL表这个领域,我想NG-模型我的文本框,设置它的异步XHR请求,并得到它。

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 gets it.

下面是一个的jsfiddle我试图把togather来模拟它,没有异步但正如我不能把它关闭:

Here is a jsfiddle I tried to put togather to simulate it, without async though as I couldn't pull it off:

<div ng-controller="MyCtrl">
        {{prefs.delay}}
        Type a number: <input type="text" ng-model="prefs.delay"/>
</div>

和脚本:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, $q, $timeout) {

    var getPref = function(prefName) {
        /*
        var deferredMain_getPref = $q.defer();

        sendAsyncMessage(['getPref', prefName], function(aPrefVal) {
                deferredMain_getPref.resolve(aPrefVal);
        });
        */
        return prefStore[prefName]
    };


    $scope.prefs = {
        delay: getPref('delay')
    };

    $scope.$watch('prefs.delay', function(newValue) {
        sendAsyncMessage(['setPref', 'delay', newValue]);
    });


}

// check global pref store value with:
// content.document.getElementsByTagName('iframe')[0].contentWindow.wrappedJSObject.prefStore
// faking stuff below for demo
var prefStore = {
    delay: 100
};
function sendAsyncMessage(arrOfFuncNameAndArgs, aCallback) {
    if (arrOfFuncNameAndArgs[0] == 'setPref') {
        prefStore[arrOfFuncNameAndArgs[1]] = arrOfFuncNameAndArgs[2];
    } else if (arrOfFuncNameAndArgs[0] == 'getPref') {
        setTimeout(function() {
            aCallback(prefStore.delay);
        }, 1000);
    }
}

的jsfiddle链接 - 演示

在此拨弄我试图伪造的滞后时间异步行为与的setTimeout 但是失败了,所以删除了异步的行为向您展示角的作品。但是,可以请你帮我介绍与超时假异步。

In this fiddle I tried to fake the lag time for async behavior with setTimeout however failed, so removed the async behavior to show you the angular works. But can you please help me introduce a fake async with timeout.

能否请您帮助我这一个。

Can you please help me figure this one out.

推荐答案

下面是在的黑暗什么,我相信你是在的一个镜头。首先, NG-模式不会prevent打字,只会触发验证。相反,通过使用输入[数字] 开始了。我的也猜测的你希望看到你在你的&LT设置手动值;输入/&GT; ,而不是键控输入。对于这一点,断火 $事件。preventDefault(),势必 NG-的keydown 。下面是一个完整的工作示例中,我裹在一个名为异步一个装饰指令。遵守以下...

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...

<input type="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();
                    });
                });
            }
        }
    }
}]);

其中,为myService 是一个嘲弄的服务利用 $ Q $超时模拟异步行为...

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

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

    function getValue () {
        var deferred = $q.defer();

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

        return deferred.promise;
    }

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

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

        return deferred.promise;
    }

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

其中, 123 - 采样值 - 异步菊花通过链接的的getValue setValue方法功能。从的getValue 也被作为参数传递给的setValue 的情况下,最后调用之前需要进一步的操作<$ C结果$ C> ngModel。$ setViewValue 和 ngModel。$渲染()。此外,你的目标是有可能利用其在的getValue请求()。所以,如果这一点,只需注入一个服务,例如 $ HTTP 并据此模型......

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链接 - 工作演示 - 键入 1 => 500毫秒=> 123

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

如果我的假设是错误的,你希望prevent键控价值进行初始,所以您可以绑定到 NG-变化和删除 $事件。preventDefault 。如果你选择了这个,你会看到你的初始类型值,那么这将改变(获取/套)如预期。

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.

这篇关于NG-模型异步我的服务器上XHR获取/设置场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆