通过服务访问控制器对象

access to controller object via service

这是我的控制器:

constructor(Auth, $http, $rootScope, $log, $scope, $uibModal, loginTemplate, demandCity, signupTemplate, socket) {
  this.isLoggedIn = Auth.isLoggedIn;
  this.$http = $http;
  this.socket = socket;
  this.awesomeDemands = [];

  $scope.newDemand = demandCity.newDemand;

    $scope.addDemand=function(){
        demandCity.addDemand()
        console.log($scope.newDemand);
    };
}

这是我的服务:

angular.module('merciPublicApp')
  .service('demandCity',['$http', 'socket', function ($http, socket) {

      this.$http = $http;
      this.socket = socket;
      this.awesomeDemands = [];

    this.addDemand = function() {
      if (this.newDemand) {
      console.log("addDemand");
        this.$http.post('/api/demands', {
          id: 30,
          city_id: this.newDemand,
          artist_id: 1,
          user_id: 1
        });
        this.newDemand = '';
        }
    }

    this.deleteDemand = function(demand) {
      this.$http.delete('/api/demands/' + demand._id);
    }
  }]);

这是我的 HTML :

<div class="postNewCityTemplate">
    <div class="hidden-xs">
        <div class="cardCity">
            <div class="cardCity-City">
                <input type="text" class="form-control" placeholder="Add a new demand here." ng-model="newDemand">
                <button ng-click="addDemand()">Add Demand</button>
            </div>
            <div>
                <p>Ajouter blablabla à la liste</p>
            </div>
        </div>
    </div>
    <div class="visible-xs">
    </div>
</div>

我想从我的控制器获取 $scope.newDemand 的内容到我的服务。 addDemand() 函数不起作用,因为 this.newDemand 是空的,我基本上需要替换 this.newDemand 但我不知道如何...

在此先感谢您对我的帮助。

您可以将数据传递给函数 demandCity.addDemand()。

在控制器中:

demandCity.addDemand($scope.newDemand);

然后服役:

 this.addDemand = function(passedNewDemand) {
      if (passedNewDemand) {
      console.log("addDemand");
        this.$http.post('/api/demands', {
          id: 30,
          city_id: this.newDemand,
          artist_id: 1,
          user_id: 1
        });
        this.newDemand = '';
        }
    }