user2975974 user2975974 - 5 months ago 17
AngularJS Question

Using Angular Service in MEANJS 0.4.2

I have a, maybe simple, problem. I worked with services in Angular before but now a ran into problems using a MEANJS Yeoman Generator project. What i need to to is to use data of an array from a specific module in another module, so that i can ng-repeat over this inside the view of the other model.

Where exactly do i bring in the array inside the service?

(function () {
'use strict';

angular
.module('patients')

.factory('PatientsService', PatientsService);

PatientsService.$inject = ['$resource'];

function PatientsService($resource) {
return $resource('api/patients/:patientId', {
patientId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
})();


I found nothing inside the MEANJS Doc so far and neither here (only from older MEANJS versions with another service structure).

Here is what i would like to bring inside the service:

// Shows a List of useable avatars on Patient creation
$scope.avatars = [
{ value:'1', name: 'modules/patients/client/img/avatar/avatar1.png' },
{ value:'2', name: 'modules/patients/client/img/avatar/avatar2.png' },
{ value:'3', name: 'modules/patients/client/img/avatar/avatar3.png' },
{ value:'4', name: 'modules/patients/client/img/avatar/avatar4.png' },
{ value:'5', name: 'modules/patients/client/img/avatar/avatar5.png' },
{ value:'6', name: 'modules/patients/client/img/avatar/avatar6.png' }
];


I would like to use the avatars in the home.client view an the PatientsService is already injected inside the home.client controller.

Answer

Your service above simply returns a $resource. Instead, the service could return a plain old Javascript object (or a class) that had various properties. Among them would be a property containing the array of avatars, and another containing the $resource:

(function () {
  'use strict';

  angular
  .module('patients')

  .factory('PatientsService', PatientsService);

  PatientsService.$inject = ['$resource'];

  function PatientsService($resource) {
    return {
      avatars: [ {value: 0, ... } ],
      resource: $resource('api/patients/:patientId', {
          patientId: '@_id'
        }, {
          update: {
            method: 'PUT'
        }
      })
    }

  }
})();
Comments