【问题标题】:Binding data after promise承诺后绑定数据
【发布时间】:2017-09-02 06:37:02
【问题描述】:

我有一个表格,其中包含一个用于激活/停用用户的按钮。当我单击该按钮时,它会调用 API 来更改用户的状态。我遇到的问题是在 API 调用后使用视图执行实时更新。目前,我看到文本切换的唯一方法是刷新页面。

这是我的 Admin.html,当单击按钮时,按钮上的文本应在“活动”和“非活动”之间切换。

<tr ng-repeat="account in $ctrl.account">
  <td>{{account.FirstName}}</td>
  <td>{{account.LastName}}</td>
  <td class="text-center">
    <button class="btn btn-sm btn-active-status" ng-class="account.Active === true ? 'btn-info' : 'btn-danger'" ng-bind="account.Active === true ? 'Active' : 'Inactive'" ng-click="$ctrl.UpdateActiveStatus(account.Id, account.Active)"></button>
  </td>
</tr>

这是我的 AdminController.js

app.component('admin', {
    templateUrl: 'Content/app/components/admin/Admin.html',
    controller: AdminController,
    bindings: {
        accounts: '='
    }
})

function AdminController(AccountService) {
    this.$onInit = function () {
        this.account = this.accounts;
    }

    this.UpdateActiveStatus = function (id, status) {
        var data = {
            Id: id,
            Active: !status
        };

        AccountService.UpdateActiveStatus(data).then(function (response) {
            AccountService.GetAccounts().then(function (data) {
                this.account = data;
            });
        });
    };
}

【问题讨论】:

  • api调用成功后,为什么要刷新整个表?您应该只更新具有给定 ID 的帐户对象
  • 不要使用this,因为它的上下文会根据调用它的函数而变化。您应该改为创建 this 的别名(即 var controller = this; 然后在回调 controller.account = data 中),或使用 ES6 箭头函数,或 .bind()
  • 好主意,我会这样做@MariaInesParnisari
  • 感谢您的提示,这使它起作用了! @克莱斯

标签: javascript html angularjs angularjs-bindings


【解决方案1】:

这是我的问题的解决方法。如果有比这更好的方法,请告诉我。

function AdminController(AccountService) {
    var controller = this;
    this.$onInit = function () {
        controller.account = this.accounts;
    }

    this.UpdateActiveStatus = function (id, status) {
        var data = {
            Id: id,
            Active: !status
        };

        AccountService.UpdateActiveStatus(data).then(function (data) {
            for (var i = 0; i < controller.account.length; i++) {
                if (controller.account[i].Id === data.Id) {
                    controller.account[i].Active = data.Active;
                }
            }
        });
    };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2018-12-06
    • 2017-11-16
    • 2013-08-13
    • 2017-08-12
    • 2015-04-15
    相关资源
    最近更新 更多