在AngularJs上删除刚刚创建的对象

时间:2016-07-24 17:14:43

标签: javascript angularjs typescript ecmascript-6

我有一个搜索列表。

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解决方案的情况下工作。有可能吗?

1 个答案:

答案 0 :(得分:3)

因为新添加的search似乎没有_id参数,因为您只是直接推送this.newSearch数组中的searches

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

我们去,而不是在本地维护,我会说,你应该重新运行get call来获取你已经在做searches函数的所有$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.
      });
  }
}