我正在使用Angular,我需要在删除一行后刷新视图。 当前代码正常工作,但Table根本没有更新。
知道如何更改我的代码吗?
'use strict'; app.controller('locationsController',['$ scope','locationsService',函数($ scope,locationsService){
$scope.locations = [];
locationsService.getLocations().then(function (results) {
$scope.locations = results.data;
}, function (error) {
//alert(error.data.message);
});
$scope.deleteLocation = function (locationId) {
locationsService.deleteLocation(locationId); // UPDATE THE VIEW
};
}]);
<div>
<div>
<table>
<thead>
<tr>
<th>Action</th>
<th>LocationId</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="location in locations">
<td>
<a href="#/login">Edit</a>
<button ng-click="deleteLocation(location.locationId);">Delete</button>
</td>
<td>
{{ location.locationId }}
</td>
<td>
{{ location.name }}
</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>LocationId</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{{ location.locationId }}
</td>
<td>
<input type="text" name="{{ location.name }}">
</td>
</tr>
</table>
</div>
</div>
'use strict';
app.factory('locationsService', ['$http', function ($http) {
var serviceBase = 'http://localhost:4014/';
var locationsServiceFactory = {};
var _getLocations = function () {
return $http.get(serviceBase + 'api/locations').then(function (results) {
return results;
});
};
var _deleteLocation = function (locationId) {
return $http.delete(serviceBase + 'api/locations/' + locationId).then(function (results) {
return results;
});
};
locationsServiceFactory.getLocations = _getLocations;
locationsServiceFactory.deleteLocation = _deleteLocation;
return locationsServiceFactory;
}]);
答案 0 :(得分:5)
HTML:
<button ng-click="deleteLocation(location.locationId, $index);">Delete</button>
JS
$scope.deleteLocation = function (locationId, index) {
locationsService.deleteLocation(locationId).then(function(){
$scope.locations.splice(index, 1)
}); // UPDATE THE VIEW
};
答案 1 :(得分:1)
试试这个:
view.html
<div>
<div>
<table>
<thead>
<tr>
<th>Action</th>
<th>LocationId</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="location in locations">
<td>
<a href="#/login">Edit</a>
<button ng-click="deleteLocation(location.locationId,$index);">Delete</button>
</td>
<td>
{{ location.locationId }}
</td>
<td>
{{ location.name }}
</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>LocationId</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>
{{ location.locationId }}
</td>
<td>
<input type="text" name="{{ location.name }}">
</td>
</tr>
</table>
</div>
Controller.js:
$scope.deleteLocation = function (locationId,index) {
return locationsService.deleteLocation(locationId).then(function()
{
$scope.locations.splice(index,1);
}); // UPDATE THE VIEW
};