gpt4 book ai didi

javascript - 删除 AngularJs 上刚刚创建的对象

转载 作者:行者123 更新时间:2023-11-28 18:28:48 24 4
gpt4 key购买 nike

我有一个搜索列表。

search.html:

<ul class="col-xs-12" ng-repeat="search in searchesCtrl.searches">
<li>
<a href="#">{{search.url}}</a><button class="btn btn-danger" ng-click="searchesCtrl.deleteSearch(search)">Delete</button>
</li>
</ul>

<div class="input-group">
<input type="text" class="form-control" ng-model="searchesCtrl.newSearch.name"/>
<input type="text" class="form-control" ng-model="searchesCtrl.newSearch.url"/>
<span class="input-group-btn">
<a class="btn btn-primary" ng-click="searchesCtrl.addNewSearch()">Go</a>
</span>
</div>

search.controller.js:

'use strict';

(function () {

class SearchesComponent {
constructor($http) {
this.$http = $http;
this.searches = [];
}

$onInit() {
this.$http.get('/api/searches')
.then(response => {
this.searches = response.data;
});
}

addNewSearch() {
if (this.newSearch) {
this.$http.post('/api/searches', {
url: this.newSearch.url,
name: this.newSearch.name
}).then(() => {
this.searches.push(this.newSearch);
this.newSearch = '';
});
}
}

deleteSearch(search) {
this.$http.delete('/api/searches/' + search._id)
.then(() => {
this.searches.splice(this.searches.indexOf(search),1);
});
}
}

angular.module('myApp')
.component('searches', {
templateUrl: 'app/searches/searches.html',
controller: SearchesComponent,
controllerAs: 'searchesCtrl'
});
})();

如果我尝试删除刚刚添加的搜索而不刷新页面,则它不起作用。
ng-click="searchesCtrl.deleteSearch(search)" 正在调用/api/searches/undefined

我尝试在没有 $index 解决方案的情况下工作。这可能吗?

最佳答案

因为新添加的search似乎没有_id参数,因为你直接在中推送this.newSearch >搜索数组。

基本上,您的添加新帖子方法应该返回一个已保存在数据库中的对象实体,并且该实体将由服务器填充正确的_id。接下来,将该新实体对象推送到 searches 数组。尽管如此,我个人还是觉得这种方法非常糟糕,因为我们假设只有一个用户来处理这个系统。因为我们只负责更新 JavaScript 中的 searches 对象。

我们开始吧,我想说的是,您应该重新运行 get 调用来获取您已经在执行的所有搜索,而不是在本地维护内容$onInit函数。因此,它将确保您在 UI 上看到的列表与服务器同步。当您删除和保存对象时,您必须调用 getSearches 方法,这是执行此操作的正确方法。

代码

class SearchesComponent {
constructor($http) {
this.$http = $http;
this.searches = [];
}

getSearches(){
this.$http.get('/api/searches')
.then(response => {
this.searches = response.data;
});
}

$onInit() {
this.getSearches(); //retrieving list of searches from server
}

addNewSearch() {
if (this.newSearch) {
this.$http.post('/api/searches', {
url: this.newSearch.url,
name: this.newSearch.name
}).then(() => {
this.getSearches(); //asking for list from server
});
}
}

deleteSearch(search) {
this.$http.delete('/api/searches/' + search._id)
.then(() => {
this.getSearches(); //asking for list from server.
});
}
}

关于javascript - 删除 AngularJs 上刚刚创建的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38554651/

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