在AngularJS承诺解决之前的功能结束


$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

我有一个带有ng-click的锚标签,该标签称为上述点击功能。我依赖于解决和更新HREF属性的承诺,但是我发现功能的终结已经到达Promise..then()()(),这会导致我的NG点击键无法正常工作,如我所期望的,HREF属性,HREF属性在HREF上的NG点击事件后进行更新。

如何解决此问题,以确保承诺的内部功能在达到此功能结束之前?

您可以使用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作为使用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;
  });
}