user6440175 user6440175 - 5 months ago 23
AngularJS Question

Angular service with parameters error

I am trying to send two variables from angular service to mvc controller. And I am getting errors all the time. Now I am getting the error that compName doesn't exist. I have been stacked for a few hour, I tried to debug it with the angular debugger but no luck so far.
I think that my error has something to do with the angular controller is trying to call the service on load instead on click, but I don't know how to fix that.

myApp.service('getDocTypesService', ['$http', '$q', function ($http, $q) {
var allSettings = null;
this.getDocTypes = function (compName, custName) {
var def = $q.defer()
if (allSettings) {
def.resolve(allSettings);
} else {
$http.post('GetDocTypes', { companyName: compName, customerName: custName })
.then(function (response) {
var response = $.parseJSON(response.data)
allSettings = response;
def.resolve(allSettings);
});
}
return def.promise;
}
}]);


This is my angular controller and the service:

myApp.controller('myController', ['$scope', 'getDocTypesService',
function ($scope, getDocTypesService) {
$scope.docSettings = '';
getDocTypesService.getDocTypes(compName, custName).then(function (value) {
$scope.docSettings = value

})

};
}
]);


This is the HTML:

<select ng-model = "selectedDocument" ng-click="getDocTypes(selectedCompany, enteredCustomer)">
<option>Select document</option>
<option ng-repeat="docSetting in docSettings" value=" {{docSetting.Doc_Type}}">{{docSetting.Doc_Type}}</option>
</select>

Answer

Try this:

controller:

$scope.getTypes = function(comp, cust) {
    getDocTypesService.getDocTypes(comp, cust).then(function (value) {
          $scope.docSettings = value
    });
};

Template:

<select ng-model = "selectedDocument" ng-click="getTypes(selectedCompany, enteredCustomer)">

Obs: selectedCompany and enteredCustomer must be $scope variables defined before the click happens.