gpt4 book ai didi

javascript - 更新提交上的范围变量并更新 Angular js中的 View

转载 作者:行者123 更新时间:2023-11-30 07:38:32 24 4
gpt4 key购买 nike

我正在用 angularjs 创建我的第一个 Web 应用程序,一旦用户在输入框中提交文本/数字,就无法使用新值更新页面。

我正在使用 Java8、MongoDB、AngularJS 和 twitter bootstrap

HTML:

<td>
<input type="text" class="form-control" placeholder="enter bugnumber" data-ng-model="auditdata.newbugnumber">

<h4>Bug Numbers</h4>

<a href="{{bugLink(a)}}" data-ng-repeat="a in parseBug(auditdata.bugnumber) track by $index">{{a}}</a>

</td>

<td>
<button type="submit" data-ng-click="add(auditdata)" class="btn btn-danger" >Save</button>
</td>

在上面的 HTML 中,我在 ng-model=auditadata.newbugnumber 中获取用户的输入,但在服务器端,它仍然会在 bugnumber 字段中获得更新。 newbugnumber 字段的作用类似于临时变量,仅用于将新数据发送到服务器。使用 temp 变量的原因是为了避免 angularjs 中的双向绑定(bind)。

我尝试在下面的JS中使用$apply()、$watch和digest,但无法获取要在 View 中更新的值。数据在 View 中更新的唯一方法是当我重新加载页面时,这不是一个选项

app.controller('listCtrl', function ($scope, $http,$route) {

$scope.isCollapsed = true;


$http.get('/api/v1/result').success(function (data) {
$scope.audit = data;

}).error(function (data, status) {
console.log('Error ' + data);
})


$scope.add= function(bugInfo) {

$http.post('/api/v1/result/updateBug', bugInfo).success(function (data) {
bugInfo.newbugnumber='';
console.log('audit data updated');

}).error(function (data, status) {
console.log('Error ' + data);
}
};
});

服务器端更新功能

public void updateAuditData(String body) {

Result updateAudit = new Gson().fromJson(body, Result.class);
audit.update(
new BasicDBObject("_id", new ObjectId(updateAudit.getId())),
new BasicDBObject("$push", new BasicDBObject().append("bugnumber",
updateAudit.getNewbugnumber())));
}

集合中归档的错误编号是什么样的

> db.audit.find({"_id" : ObjectId("5696e2cee4b05e970b5a0a68")})
{
"bugnumber" : [
"789000",
"1212"
]
}

最佳答案

根据您的评论,执行以下操作:

将所有 $http 处理放在服务或工厂中。这是一个很好的实践,可以使重用和测试变得更容易

app.factory('AuditService', function($http) {
var get = function() {
return $http.get("/api/...") // returns a promise
};

var add = function() {
return $http.post("/api/...") // returns a promise
};

return {
get: get,
add: add
}
});

然后在你的 Controller 中

// note the import of AuditService
app.controller('listCtrl', function ($scope, $http,$route, AuditService) {

// other code here


// If insert is successful, then update $scope by calling the newly updated collection.
// (this is chaining the events using then())
$scope.add = function(bugInfo) {
AuditService.add().then(
function(){ // successcallback
AuditService.get().then(
function(data){ // success
$scope.audit = data;
},
function(){ // error
console.log('error reading data ' + error)
})
},
function(error){ // errorcallback
console.log('error inserting data ' + error)
})
});

相同的方法可以应用于所有 CRUD 操作

关于javascript - 更新提交上的范围变量并更新 Angular js中的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35024381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com