3

访问控制器对象这是我的控制器:通过服务

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

在此先感谢帮助我。

回答

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 = ''; 
     } 
    } 
+0

工作吧!完美的答案,非常感谢。 –

+0

太好了。请接受答案。 – Don

+0

是的,别担心,我知道,但他们告诉我等待,然后才能接受:) –