angularjs 1.5 service not triggered

74 views Asked by At

I have a form in view1, with multiple input fields. Button submit successfully posts data (stores in db), however the controller (ListController) does not seem to call a service's getter successfully.

In view2, nothing is displayed when calling job or 'summaryService.job' - not even "undefined" as initially declared in the service.

I'm using a routeProvider function in app.js - does this maybe interfere with calling services and controllers? The rest of the controllers work fine - just not the communication between the controllers and the services. Or is ng-click not a good way to trigger the setter service?

view1:

<form name="campaignForm1" action="#/setup-step2" ng-submit="setJobtitle(campaign.jobtitle); submitForm(campaign);">
<table>
 <tr>
  <td>Job title: </td>
  <td><input type="text" name="jobtitle" ng-model="campaign.jobtitle"></td>
 </tr>
 <tr>
  <td>ID: </td>
  <td><input type="text" name="id" ng-model="campaign.vacancyid"></td>
 </tr>
</table>
<button ng-click="setJobtitle(campaign.jobtitle); submitForm(campaign)" > Proceed </button>

controller view 1:

ctr.controller('Step1Controller',
    ['$scope', '$routeParams', '$http', '$location', 'summaryService' function($scope, $routeParams, $http, $location, summaryService)
                {
                    $scope.setJobtitle = function(jobtitle) {
                        summaryService.setJobtitle(jobtitle);
                    };
    ]);

service summaryService:

app.service('summaryService', function() {

this.job = "undefined";  
return {
    getJobtitle: function() {
       return this.job;
   },
   setJobtitle: function(value) {
       this.job = value
   }
};
});

View 2 does not show anything, no matter whether i call {{job}} or {{summaryService.getJobtitle()}}.

Controller view 2:

ctr.controller('ListController',
    ['$scope', 'Test', 'summaryService', function ($scope, Test, summaryService)
                    { 
                        $scope.job = summaryService.getJobtitle();
}]);

I suspect that there is something wrong with passing and calling values from within the controllers?

Git link https://github.com/2dorian/cmx

1

There are 1 answers

7
maksimr On

In your example this inside getJobtitle referret to returned object so to fix this problem you could:

1.

app.service('summaryService', function() {
this.job = "undefined";  
this.getJobtitle = function() {
       return this.job;
};
this.setJobtitle = function(value) {
       this.job = value
 };
});

or

2.

app.service('summaryService', function() {
return {
  job: "undefined",  
  getJobtitle: function() {
       return this.job;
  },
  setJobtitle: function(value) {
       this.job = value
  }
};
});

Worked example on codepen - http://codepen.io/maksimr/pen/oYmjmB