簡體   English   中英

如何在AngularJS的$ timeout中使用$ scope?

[英]How to use $scope inside $timeout with AngularJS?

我正在嘗試使用AngularJS在textarea上呈現默認消息。 我嘗試添加的某些值需要使用$timeout來獲取值。

該消息似乎無法使用以下代碼呈現:

    <textarea class="text-input referral-message" ng-init="message=buildMessage(purchase_count)" 
              ng-model="message" rows="5">
    </textarea>

$timeout(function() {

    ReferralService.settings().$promise.then(function(settings) {
        $scope.purchase_count = settings.credits;
    });

    $scope.buildMessage = function(val){
      return "Buy " + val + " and get 1 free for every purchase"
    }
}, 1);

查找scope.apply函數,然后嘗試執行以下操作(我是從內存中編寫此代碼的,不要指望它能完全起作用):

ReferralService.settings().$promise.then(function(settings) {
  $scope.$apply(function(){
     $scope.message = "Buy " + settings.credits + " and get 1 free for every purchase";
  });
});

和:

<textarea class="text-input referral-message" ng-model="message" rows="5">
</textarea>

編輯:考慮到$ timeout可能沒有必要。

Edit2:看看將ReferalService實施為工廠( angular.service與angular.factory ),我也可能會為您提供幫助。

您可以使用{{}}來顯示數據模型中的內容

<textarea class="text-input referral-message" rows="5">{{message}}
</textarea>

$timeout(function() {

ReferralService.settings().$promise.then(function(settings) {
    $scope.purchase_count = settings.credits;
    $scope.message = "Buy " + $scope.purchase_count + " and get 1 free for every purchase"
});

}, 1);

在您的情況下使用ngInit並不是一個好習慣,因為它會在模板中添加不必要的邏輯。

只需從textarea刪除ng-init ,並在解決承諾后初始化您的message變量:

ReferralService.settings().$promise.then(function (settings) {
    $scope.message = buildMessage(settings.credits);
});

function buildMessage(val) {
    return "Buy " + val + " and get 1 free for every purchase"
}

暫無
暫無

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

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