2016-12-04 1 views
0
$scope.clickfunction = function(arg){ 
    var url =""; 
    var httppromise = $scope.promiseufunction(arg); // return a http promise 
    httppromise.then(function(res){ 
    if(res){ 
     url ="path/" 
     $('#htmlelement').attr('href', url); 
     }else{ 
     url="path2/" 
      $('#htmlelement').attr('href', url); 
     }; 
     }); 
     } //<---- this line execute before the inner function of promise.then 

위의 clickfunction 함수를 호출하는 ng-click 태그가 있습니다. href 속성을 확인하고 업데이트하겠다는 약속에 의존하고 있지만 promise.then() 함수가 끝나기 전에 함수의 끝 부분에 도달하여 예상대로 ng-click이 제대로 작동하지 않는 것으로 나타났습니다. href href의 ng-click 이벤트 후에 속성이 업데이트되었습니다.angularjs 약속 완료 전에 함수 종료

어떻게이 문제를 해결할 수 있습니까? 약속 기능의 내부 기능이이 기능의 끝 부분에 도달했는지 확인하려면 어떻게해야합니까?

+2

이 어떻게 비동기 프로그래밍 작품이다. 내부 'then'함수는 HTTP 요청이 완료된 이후 단계에서 호출됩니다. – ZeMoon

+0

ur 코드가 실행됩니까? 구문 오류가있는 것 같습니다 – Mohayemin

+0

고마워요. 내가 어떻게 변경했는지, 내 제안을 어떻게 바꿀 수 있었는가? – GlassMan

답변

0

약속이 해결되면 ng-href을 사용하여 href를 업데이트 할 수 있습니다. 다음은 개념을 시뮬레이션 한 것입니다. 약속을 사용하여 값을 채 웁니다 모델 속성을 사용으로

var app = angular.module("sampleApp", []); 
 

 
app.controller("sampleController", ["$scope", "$timeout", 
 
    function($scope, $timeout) { 
 
    // Simulating the variable update at a later point. 
 
    $timeout(function() { 
 
     $scope.testUrl = "http://stackoverflow.com"; 
 
    }, 3000) 
 
    } 
 
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> 
 
<div ng-app="sampleApp"> 
 
    <div ng-controller="sampleController as vm"> 
 
    <a ng-href="{{testUrl}}">Google</a> 
 
    </div>

그래서, 참고로 위의 방법을 유지, 당신은 #htmlElement에 ngHRef를 사용할 수 있습니다.

HTML

<a ng-href="newHref">Some anchor </a> 

JS

$scope.clickfunction = function(arg) { 
    var url = ""; 
    var httppromise = $scope.promiseufunction(arg); // return a http promise 
    httppromise.then(function(res) { 
    if (res) { 
     url = "path/"; 
    } else { 
     url = "path2/" 
    }; 
    $scope.newHref = url; 
    }); 
} 
+0

고마워. href atrribute가 ng-click.i보다 우선 순위가 높기 때문에 마침내 내 문제가 있음을 발견했습니다. href attrbute 대신 window.location을 사용합니다. – GlassMan

관련 문제