簡體   English   中英

AngularJS從指令設置函數的同步調用

[英]AngularJS set synchronous call of function from directive

我有這個指令:

app.directive('changemonth', function($animator) {
    return {
      link : function($scope, element, attrs) {
        element.bind("click", function() {

          if(element.attr('class').search('disabled') == -1) {

            // récupération du calendrier :
            if(element.attr('class').search('day') != -1)
              var calendar = angular.element(element.parent().parent());
            else                                         
              var calendar = angular.element(element.parent().parent().next().children()[1]);
            var animator = $animator($scope, attrs);

            animator.hide(calendar); 
            setTimeout(function() { 
              $scope.$apply(attrs.changemonth);
              animator.show(calendar); 
            }, 500);
          }
        });
      }
    };
});

使用attrs.changemonth ,我調用一個函數(可以更改),例如:

$scope.next = function() {
        var tmpMonth = $scope.monthsLabels.indexOf($scope.monthDisplayed) + 1;
        var tmpYear = $scope.yearDisplayed;
        if(tmpMonth==12) {
            tmpMonth = 0;
            tmpYear = parseInt($scope.yearDisplayed) + 1;
        }
        getCalendar(tmpMonth, tmpYear);
        $scope.monthDisplayed = $scope.monthsLabels[tmpMonth];
        $scope.yearDisplayed = tmpYear.toString();
    };

因此,此函數調用另一個getCalendar()您可以在這里看到:

function getCalendar(month, year) {
        $http({
            method : "GET", 
            url : 'http://my_url/getCalendar', 
            params : { 
                group_id : $scope.group_id,
                month : month,
                year : year
            }
        })
        .success(function(data) {
            $scope.calendar = data;
        });
    }

getCalendar()使用$http從數據庫獲取日歷。

我的問題是我想在指令中使用animator之前等待$http的響應,像這樣,我的日歷僅在內容加載后才會顯示。

我聽說過$q和諾言。 但是我看不到如何在非常特殊的環境中使用它。

如果這里有人有一個主意,那將是非常棒的。

嘗試像這樣從成功回調中進行廣播。

.success(function(data) {
    $scope.calendar = data;
    $rootScope.$broadcast('event:calendar-received');
});

然后在您的指令中,您可以等待接收這樣的信號。

$scope.$on('event:calendar-received', function() {
    ... do your stuff with animator...
});

$http(...)計算為一個承諾。 這意味着給定

var x = $http(...)

你可以做

x.then(function success(){...}, function failure(){...});

successfailure函數將僅在兌現承諾后才被調用。 請參閱promise API

您的函數可以返回這個x並且它們的調用函數可以作為一個承諾與之交互。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM