承诺后绑定数据

时间:2017-04-07 02:16:34

标签: javascript html angularjs angularjs-bindings

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

以下是我的 Admin.html ,其中按钮上的文字应在' Active'之间切换。和'无效'单击按钮时。

<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;
            });
        });
    };
}

1 个答案:

答案 0 :(得分:0)

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

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;
                }
            }
        });
    };
}