通过服务访问控制器对象

时间:2016-08-03 14:35:43

标签: angularjs post angular-ngmodel angular-services angular-components

这是我的控制者:

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但我不知道如何...

先谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您可以将数据传递给函数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 = '';
        }
    }