【问题标题】:Failure binding Angular promise to $scope change将 Angular 承诺绑定到 $scope 更改失败
【发布时间】:2015-01-13 03:30:12
【问题描述】:

在使用 ngTagsInput 时,我遇到了将 Promise 绑定到 <autocomplete source='fnPromise()'> 的问题。我不认为ngTagsInput 有什么问题;我认为我对范围和承诺的理解不够深入,无法理解如何做我想做的事情。

我正常设置指令:

<tags-input ng-model="token.ids.tags"
            class="form-field no-animate tag-input"
            placeholder="Delete unwanted IDs"
            addFromAutocompleteOnly="true">
    <auto-complete source="offerTags($query)"></auto-complete>
</tags-input>

问题在于 offerTags() 函数。这会返回一个 Promise,但是因为我想用这个控制器的 $scope 的一部分来填充自动完成功能,所以我告诉 Promise 只返回那个 $scope 属性:

$scope.offerTags=function(query) {
    var deferred=$q.defer();

    var tags=$scope.token.ids.tags;
    deferred.resolve( tags);
    return deferred.promise;
}

但是,$scope.token.ids.tags 仅在服务返回后(页面加载后)才会填充。所以发生的事情是 offerTags 总是返回一个空数组。承诺不会使用 token.ids.tags 服务的新值进行更新。

编辑:Plunkr demonstrating problem

即,如果您将 $scope.token.ids.tags 替换为静态数组,则自动完成功能会起作用,但只有该静态数组的内容。

抱歉,解释太长了……知道如何让它工作吗?

【问题讨论】:

  • 我们可以看到服务吗?它是在回报一个承诺吗?
  • offerTags(上面引用)是返回承诺的服务。 $scope.token.ids.tags 作为 $http 请求的回调在各个地方更新。
  • 我猜 ngTagsInput 在这里是一个红鲱鱼 - 问题是承诺不反映 $scope 的变化价值。
  • 请发布更多代码或插件
  • 好的,我同意你的看法。我修复了我的 plunkr plnkr.co/edit/4Xurq1?p=preview 并解决了问题。

标签: javascript angularjs


【解决方案1】:

您的服务应该如下所示:

app.factory('TokenService', function ($http) {
    return {
        loadTags: function (query) {
          return $http.get('/query', {
            params: {
             q: query
            }
          }).then(function(res){
            return res.data;
          });
        }
    }
});

把它放在范围内:

$scope.loadTags = TokenService.loadTags;

还有模板:

<tags-input ng-model="tags">
  <auto-complete source="loadTags($query)"></auto-complete>
</tags-input>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 2021-06-29
    • 2017-11-16
    • 2018-12-28
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    相关资源
    最近更新 更多