【发布时间】:2019-05-11 00:44:18
【问题描述】:
我是 angular-js 的新手,正在构建一个简单的待办事项应用程序。我正在创建一个任务并使用 ng-repeat 在 html 表中显示创建的任务。但问题是发布数据后,$scope.tasks 变量在控制器端更新,但不在视图中。仅刷新网页后视图会更新,并将任务添加到 html 表中。创建任务后如何更新视图。提前致谢。这是我的代码:
在我的控制器中:
var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);
app.controller('DemoCtrl', function($scope,$mdSidenav,$mdDialog,$interval,$http,$mdToast) {
$scope.tasks = [];
_refreshTaskData(); //initial refresh
$scope.submitForm = function() {
var description = "";
var taskId = "";
$scope.formData = {
taskId: $scope.taskId,
description: $scope.description,
};
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(_success, _error);
};
function _refreshTaskData() {
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(res) { // error
console.log("Error: " + res.status + " : " + res.data);
});
}
function _success(res) {
$mdDialog.hide();
console.log('in success function');
_refreshTaskData(); ;
}
function _error(res) {
//error handling
}
});
在我看来:
<table>
<tr ng-repeat=" t in tasks">
<td>{{t.id}}</td>
<td>{{t.description}}</td>
</tr>
</table>
【问题讨论】:
-
更正你的html模板
{{t.description}}并使用track by $indexng-repeat=" t in tasks track by $index"