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

I have an anchor tag with ng-click that calls the above clickfunction function. I rely on the promise to resolve and update the href attribute, but I found that the end of function have reached before the innner function of promise.then(), and that causes my ng-click not work properly as i expected , href attribute updated after the ng-click event on href.

How can solve this,to make sure the inner function of promise work before reach the end of this function?

GlassMan
  • 31
  • 6
  • 2
    This is how Asynchronous programming works. The inner 'then' function gets called at a later stage after your HTTP request has completed. – ZeMoon Dec 04 '16 at 05:49
  • does ur code run? It seems to have syntax errors – Mohayemin Dec 04 '16 at 05:57
  • Thanks. I changed, any suggestion how could i rewrite this to work my ng-click properly – GlassMan Dec 04 '16 at 06:06
  • first read this question: http://stackoverflow.com/questions/33941322/angularjs-return-issue-in-response-of-http , then take a look for this one: http://stackoverflow.com/questions/33984823/angularjs-http-result-with-promise – Vahid Najafi Dec 04 '16 at 07:14

1 Answers1

0

You could use ng-href to update the href once the promise is resolved. Here is a simulation of the concept.

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>

So, keeping the above way as a reference, you could use ngHRef on the #htmlElement as use a model property that populates the value using a promise.

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;
  });
}
Sreekanth
  • 3,110
  • 10
  • 22
  • thanks guy. I finally found my problem is because that href atrribute is taking higher priority than ng-click.i use window.location instead of update the href attrbute – GlassMan Dec 05 '16 at 10:41