Louis Gls Louis Gls - 4 months ago 10
AngularJS Question

access to controller object via service

This is my controller :

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);
};
}


This is my service :

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);
}
}]);


This is my 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>


I want to get the content of $scope.newDemand from my controller to my service. The addDemand() function is not working because this.newDemand is empty, I basically need to replace this.newDemand but I don't know how...

Thanks in advance for helping me.

Don Don
Answer

You can pass data to function demandCity.addDemand().

In Controller:

demandCity.addDemand($scope.newDemand);

then in service :

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