programing

Angular JS: 약속에 구속하는 방법

fastcode 2023. 3. 31. 22:52
반응형

Angular JS: 약속에 구속하는 방법

나는 약속을 견해에 묶으려고 한다.네가 직접 할 수 있을지는 모르겠지만, 그게 내가 하려고 하는 거야.내가 뭘 잘못하고 있는지 알기나 해?

주의: 소스는 타임아웃에 약간 영향을 받아 정적 데이터를 사용하지만, 이는 코드를 진단하기 쉽게 하기 위한 것입니다.

편집: JSFiddle 페이지: http://jsfiddle.net/YQwaf/27/

편집: 솔루션: 약속을 직접 바인드할 수 있음이 밝혀졌습니다.원래 코드에 두 가지 문제가 있었습니다.

  1. angular의 $timeout 대신 setTimeout()을 사용하는 것은 문제가 있었습니다.Angular는 타임아웃이 발생했을 때 UI를 새로 고칠 필요가 없다는 것을 알지 못합니다($scope로 해결할 수 있습니다).$apply in set Timeout 또는 $timeout)을 사용할 수 있습니다.
  2. 약속을 반환하는 함수에 바인딩하는 것이 문제가 되었습니다.또 한 번 불리면 또 다른 약속을 하는 거죠.약속에 범위 변수를 설정하고 필요에 따라 새로운 약속만 만드는 것이 좋습니다.(저의 경우 $scope라고 부릅니다.$watch on the Country Code)

HTML:

<div ng:controller="addressValidationController">
    Region Code <select ng:model="regionCode" ng:options="r.code as r.name for r in getRegions()"/>
    Country Code<select ng:model="countryCode"><option value="US">United States</option><option value="CA">Canada</option></select>
</div>

JS:

function addressValidationController($scope, $q) {
    var regions = {
        US: [{code: 'WI',name: 'Wisconsin'}, {code: 'MN',name: 'Minnesota'}], 
        CA: [{code: 'ON',name: 'Ontario'}]
    };
    $scope.getRegions = function () {
        var deferred = $q.defer();
        setTimeout(function () {
            var countryRegions = regions[$scope.countryCode];
            console.log(countryRegions);
            if(countryRegions === undefined) {
                deferred.resolve([]);
            } else {
                deferred.resolve(countryRegions);
            }
        }, 1000);
        return deferred.promise;
    };
}

Angular 1.2부터는 템플릿에서 직접 약속을 사용할 없습니다.
대신, 그 결과를 다음과 같이 입력해야 합니다.$scope안에서.then보통 때처럼요. 마법은 없어요.

오래된 동작을 얻기 위한 임시 회피책으로

$parseProvider.unwrapPromises(true)

이 기능은 나중에 삭제될 예정이니 기대하지 마세요.

경고: 이 답변은 작성 시 정확하지만 1.2에서는 Angular 템플릿엔진은 약속을 투과적으로 처리하지 않습니다.- @Malvolio

템플릿 엔진(및 식)은 약속을 투과적으로 처리하지만 컨트롤러의 스코프 속성에 약속을 할당하고 새로운 약속을 반환하는 함수를 호출할 때마다 해당 약속을 호출하지 않습니다(고객의 문제라고 생각합니다.매번 새로운 약속이 반환되기 때문에 해결된 약속은 손실됩니다).

JSFiddle:http://jsfiddle.net/YQwaf/36/

HTML:

<div ng:controller="addressValidationController">
    Region Code <select ng:model="regionCode" ng:options="r.code as r.name for r in regions"/>
    Country Code<select ng:model="countryCode"><option value="US">United States</option><option value="CA">Canada</option></select>
</div>

JS:

function addressValidationController($scope, $q, $timeout) {
    var regions = {
        US: [{
            code: 'WI',
            name: 'Wisconsin'},
        {
            code: 'MN',
            name: 'Minnesota'}],
        CA: [{
            code: 'ON',
            name: 'Ontario'}]
    };

    function getRegions(countryCode) {
        console.log('getRegions: ' + countryCode);
        var deferred = $q.defer();
        $timeout(function() {
            var countryRegions = regions[countryCode];
            if (countryRegions === undefined) {
                console.log('resolve empty');
                deferred.resolve([]);
            } else {
                console.log('resolve');
                deferred.resolve(countryRegions);
            }
        }, 1000);
        return deferred.promise;
    };

    $scope.regions = [];

    // Manage country changes:
    $scope.$watch('countryCode', function(countryCode) {
        if (angular.isDefined(countryCode)) {
            $scope.regions = getRegions(countryCode);
        }
        else {
            $scope.regions = [];
        }
    });
}​

각도 1.3 기준 -$parseProvider.unwrapPromises(true) 더 이상 작동하지 않습니다.

대신 직접 약속을 풀어야 합니다.

myApiMethod().then(function(value){
    $scope.item = value; 
});

약속 언랩은 ngResource에서 정상적으로 동작합니다.

목록을 유지하는 범위 변수에 대한 참조를 반환하면 충분합니다.

function addressValidationController($scope,$timeout) {
    var regions = {
        US: [{code: 'WI',name: 'Wisconsin'}, {code: 'MN',name: 'Minnesota'}], 
        CA: [{code: 'ON',name: 'Ontario'}]
    };

    $scope._regions = [];

    $scope.getRegions = function () {

        $timeout(function () {
            var countryRegions = regions[$scope.countryCode];
            console.log(countryRegions);
            if(countryRegions === undefined) {
                $scope._regions = []
            } else {
                $scope._regions = countryRegions
            }
        }, 1000);

        return $scope._regions;
    };
}

언급URL : https://stackoverflow.com/questions/13033118/angular-js-how-to-bind-to-promises

반응형