【发布时间】: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