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> 

Я хочу, чтобы получить content of $ 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

Да, не беспокойтесь, я знаю, но они говорят мне подождать, прежде чем я смогу принять :) –

Смежные вопросы