我正在 angularjs 中开发我的第一个应用程序,每当我单击按钮时,应用程序都会刷新数据库中的所有行,即使我没有要求它这样做,但我遇到了问题。 数据源中的每一行都有一个“阻止”按钮。如果我单击该按钮,模型中的该行将被标记为正确阻止并重新设计样式,但随后所有行都会从数据源刷新,覆盖客户端的更改。为什么会出现这种情况?
完整代码:
<script>
var bookingAppModule = angular.module('bookingApp',[]);
bookingAppModule.controller('bookingController', ['$scope', '$http', function ($scope, $http) {
$scope.bookingDate = '<%= DateTime.Today.Year %>/<%= DateTime.Today.Month %>/<%= DateTime.Today.Day %>';
$scope.getAppointments = function () {
var response = $http.post('/api/Appointments', "'" + $scope.bookingDate + "'" );
response.success(function (data, status, headers, config) {
$scope.appointments = data;
});
response.error(function (data, status, headers, config) {
alert('Something went wrong...');
});
};
$scope.appointments = $scope.getAppointments();
$scope.blockSlot = function (slot) {
slot.blocked = true;
};
$scope.bookSlot = function (slot) {
alert("booking slot " + slotId);
}
}]);
</script>
<div id ="booking-app" ng-app="bookingApp">
<div id="service-select">
<label for='<%= ddlService.ClientID %>'>Select service:</label>
<asp:DropDownList ID="ddlService" runat="server" DataTextField="Description" DataValueField="Id" OnSelectedIndexChanged ="ddlService_SelectedIndexChanged" AutoPostBack="false" >
</asp:DropDownList>
</div>
<div ng-controller="bookingController">
<input type="date" ng-model="bookingDate" ng-change="getAppointments()" />
<div class ="appt-day">
<div ng-repeat="shift in appointments">
<div class="appt-counsellor">
<h2>{{shift.counsellor}}</h2>
</div>
<div ng-repeat ="slot in shift.slots" class="appt-row clearfix" ng-class="{'blocked' : slot.blocked}" >
<div class="appt-time">{{slot.time}}</div>
<div class="appt-desc">{{slot.clientName}}</div>
<button class="appt-btn mla-button" ng-class="{'show' : !slot.blocked}" ng-click="bookSlot(slot)">Book</button>
<button class="appt-btn mla-button" ng-class="{'show' : !slot.blocked}" ng-click ="blockSlot(slot)">Block</button>
</div>
</div>
</div>
</div>
最佳答案
发生这种情况是因为单击按钮时您重写了 $scope.appointments,并且“阻止”属性不会保存。 为了解决这个问题,您可以将“blocked”属性本地存储在其他数组中,并在调用 $scope.getAppointments 时将此属性写入每个“约会”对象。 另一种方法是,仅刷新服务器上已更改的约会 - 并且您的“阻止”属性将被保存。
关于javascript - 为什么当我单击按钮时,我的 Angular 应用程序会刷新数据源中的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23378417/