I have a list of searches.
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'
});
})();
If I try to remove a search that I just have added, without refreshing the page, it's not working.
The ng-click="searchesCtrl.deleteSearch(search)" is calling
/api/searches/undefined.
I try to work without the $index solution. Is it possible ?
functionare you gettingundefined?$http.post('/api/searches'..).then(newSearch => ...? You need to getsearch._idfrom the server somehow.$http.postin youraddNewSearchfunction, otherwise yourdeletewilln't work.