Using Angular Service in MEANJS 0.4.2 - angularjs

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.

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

Related

Unit testing promises in js-data-angular models

We use js-data and js-data-angular in our project.
I have the following model:
(function () {
'use strict';
angular.module('dash.models')
.factory('Diagnosis', ['DS', function (DS) {
function transform(resourcename, attrs, cb) {
attrs.icd9codes.forEach(function (el) {
delete el.add;
});
cb(null, attrs);
}
this.transform = transform;
return DS.defineResource({
name: 'diagnosis',
idAttribute: 'id',
endpoint: '/diagnosis',
baseUrl: '/api',
beforeCreate: transform,
beforeUpdate: transform
});
}]);
}());
And the following call to said model:
var startEditing = self.startEditing = function(parentScope, diagnosis) {
Diagnosis.findAll({
deep:true
}, {
endpoint: '/diagnosis/' + diagnosis.id
}).then(function(d) {
$scope.diagnosis = d;
$scope.inScope = true;
});
};
In my unit test, I mock the call like this:
var diagDeferred = _$q_.defer();
diagDeferred.resolve({
'name': 'Breast',
'categories': null,
'id': '026c7cd0-14ef-4312-a8f1-2092107b0e50',
'icd9codes': [{id: '1', code: '001', description: 'ICD9 Code'}]
});
spyOn(Diagnosis, 'findAll').and.returnValue(diagDeferred.promise);
And the actual call is mocked, what doesn't get executed (and I can't find any reliable information on how to get this done) is the function inside the .then of the Diagnosis.findAll
I know the code works, but I need to cover it with unit tests and I'm coming up dry.
Thanks.
I think you forgot to call $scope.digest() in your test. Here is a working fiddle.
After you call startEditing(), you should call $scope.$digest() so that your mock promise is executed and you can get your data in then block. Hope it helps.

AngularJS REST service calls

I'm looking to add factory/service calls for the URLs below to an AngularJS project in a way that follows the DRY principle. The project uses ngResource.
http://localhost/vehicles/{type:car|truck}/drive/{2wd|4wd}?sort={"start":"1", "limit':"10", "sortBy": "make"}
http://localhost/vehicles/{type:car|truck}/drive/{2wd|4wd}/count
http://localhost/vehicles/bestselling/{type:car|truck}?sort={"start":"1", "limit':"10", "sortBy": "make"}
http://localhost/vehicles/bestselling/{type:car|truck}/count
All calls are HTTP GET
The URL path parameters "{type:car|truck}" can be either one of "car" or "truck" the same goes for "{2wd|4wd}".
The URLs ending with count return the number of items (for pagination); the rest return the list of items to be displayed.
How can I define the factory/service calls for these resources in Angular? I have not had any luck finding an answer for this; the closest I've found is this
Disclaimer: I have no experience with AngularJS
My solution:
services.js
resources.factory('Constants', [
function() {
return {
RESOURCE_URL: "http://localhost/vehicles"
}
}
]);
resources.factory('Rest', ['Constants', '$resource', function(C, $resource) {
return {
BestSellingCount: $resource(C.RESOURCE_URL + '/bestselling/:type/count', {
type: '#type'},{})
BestSelling: $resource(C.RESOURCE_URL + '/bestselling/:type', {
type: '#type'}, {
getBestSelling: { method:'GET', params: {sort: {"start":"1", "limit':"10", "sortBy": "make"}}, isArray: true)}}})
}]);
And in my controller
$scope.bestsellingtrucks = Rest.BestSelling.getBestSelling({type:"truck"});
The default sort and pagination values get passed in as a query string

Configure restmod for submodule in AngularJS

So I have a main module app defined as
app = angular.module("app", ['app.social_accounts', 'restmod'])
which has its restmod module configured:
app.config(function(restmodProvider) {
restmodProvider.rebase({
$config: {
primaryKey: "id",
style: "ams",
urlPrefix: "/app/"
}
});
});
and it works as expected: request were sent to http://localhost:8000/app/...
Now I want to use restmod in the submodule app.social_accounts, by doing
app = angular.module("app.social_accounts", ['restmod'])
app.config(function(restmodProvider) {
restmodProvider.rebase({
$config: {
primaryKey: "id",
style: "ams",
urlPrefix: "https://graph.facebook.com/"
}
});
});
app.factory("Album", ["restmod", function(restmod){
Album = restmod.model("/me/albums/")
return {
"get": function(){Album.$search()}
}
}])
namely I want to use absolute url in the submodule app.social_accounts.
But when I inject Album (registered under app.social_accounts) into a controller DashboardCtrl under app, the request were sent to http://localhost:8000/app/me/albums/.
So I wonder what is happening here and how to achieve a separate url for restmod under app.social_accounts?
Any configuration defined with restmodProvider is global for restmod irrespective of the module it's used in. So in your example above, the urlPrefix defined in the app.social_accounts module is being overwritten by the configuration in the app module.
In order to achieve the behaviour you expect, you can override the configuration on a per model basis:
angular.module('app.social_accounts', ['restmod'])
.factory('Album', function(restmod) {
var Album = restmod.model('/me/albums')
.mix({
$config: {
urlPrefix: 'https://graph.facebook.com/'
}
});
});
If you require the configuration in more than one model within a module, a mixin can be used to keep things DRY:
.factory('restmodConfigSocial', function(restmod) {
return restmod.mixin({
$config: {
urlPrefix: 'https://graph.facebook.com/'
}
});
})
.factory('Album', function(restmod) {
var Album = restmod.model('/me/albums').mix('restmodConfigSocial');
});

Proper place for data-saving logic in AngularJS

App design question. I have a project which has a very large number of highly customized inputs. Each input is implemented as a directive (and Angular has made this an absolute joy to develop).
The inputs save their data upon blur, so there's no form to submit. That's been working great.
Each input has an attribute called "saveable" which drives another directive which is shared by all these input types. the Saveable directive uses a $resource to post data back to the API.
My question is, should this logic be in a directive at all? I initially put it there because I thought I would need the saving logic in multiple controllers, but it turns out they're really happening in the same one. Also, I read somewhere (lost the reference) that the directive is a bad place to put API logic.
Additionally, I need to introduce unit testing for this saving logic soon, and testing controllers seems much more straightforward than testing directives.
Thanks in advance; Angular's documentation may be… iffy… but the folks in the community are mega-rad.
[edit] a non-functional, simplified look at what I'm doing:
<input ng-model="question.value" some-input-type-directive saveable ng-blur="saveModel(question)">
.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{id: question.id, answer: question.value},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
}
}])
No, I don't think the directive should be calling $http. I would create a service (using the factory in Angular) OR (preferably) a model. When it is in a model, I prefer to use the $resource service to define my model "classes". Then, I abstract the $http/REST code into a nice, active model.
The typical answer for this is that you should use a service for this purpose. Here's some general information about this: http://docs.angularjs.org/guide/dev_guide.services.understanding_services
Here is a plunk with code modeled after your own starting example:
Example code:
var app = angular.module('savingServiceDemo', []);
app.service('savingService', function() {
return {
somethingOrOther: {
save: function(obj, callback) {
console.log('Saved:');
console.dir(obj);
callback(obj, {});
}
}
};
});
app.directive('saveable', ['savingService', function(savingService) {
return {
restrict: 'A',
link: function(scope) {
scope.saveModel = function(question) {
savingService.somethingOrOther.save(
{
id: question.id,
answer: question.value
},
function(response, getResponseHeaders) {
// a bunch of post-processing
}
);
}
}
};
}]);
app.controller('questionController', ['$scope', function($scope) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
}]);
The relevant HTML markup:
<body ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="saveModel(question)" />
</body>
An alternative using only factory and the existing ngResource service:
However, you could also utilize factory and ngResource in a way that would let you reuse some of the common "saving logic", while still giving you the ability to provide variation for distinct types of objects / data that you wish to save or query. And, this way still results in just a single instantiation of the saver for your specific object type.
Example using MongoLab collections
I've done something like this to make it easier to use MongoLab collections.
Here's a plunk.
The gist of the idea is this snippet:
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
Notes:
dbUrl and apiKey would be, of course, specific to your own MongoLab info
The array in this case is a group of distinct collections that you want individual ngResource-derived instances of
There is a createResource function defined (which you can see in the plunk and in the code below) that actually handles creating a constructor with an ngResource prototype.
If you wanted, you could modify the svc instance to vary its behavior by collection type
When you blur the input field, this will invoke the dummy consoleLog function and just write some debug info to the console for illustration purposes.
This also prints the number of times the createResource function itself was called, as a way to demonstrate that, even though there are actually two controllers, questionController and questionController2 asking for the same injections, the factories get called only 3 times in total.
Note: updateSafe is a function I like to use with MongoLab that allows you to apply a partial update, basically a PATCH. Otherwise, if you only send a few properties, the entire document will get overwritten with ONLY those properties! No good!
Full code:
HTML:
<body>
<div ng-controller="questionController">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
<div ng-controller="questionController2">
<h3>Question<h3>
<h4>{{question.question}}</h4>
Your answer: <input ng-model="question.value" saveable ng-blur="save(question)" />
</div>
</body>
JavaScript:
(function() {
var app = angular.module('savingServiceDemo', ['ngResource']);
var numberOfTimesCreateResourceGetsInvokedShouldStopAt3 = 0;
function createResource(resourceService, resourcePath, resourceName, apiKey) {
numberOfTimesCreateResourceGetsInvokedShouldStopAt3++;
var resource = resourceService(resourcePath + '/' + resourceName + '/:id',
{
apiKey: apiKey
},
{
update:
{
method: 'PUT'
}
}
);
resource.prototype.consoleLog = function (val, cb) {
console.log("The numberOfTimesCreateResourceGetsInvokedShouldStopAt3 counter is at: " + numberOfTimesCreateResourceGetsInvokedShouldStopAt3);
console.log('Logging:');
console.log(val);
console.log('this =');
console.log(this);
if (cb) {
cb();
}
};
resource.prototype.update = function (cb) {
return resource.update({
id: this._id.$oid
},
angular.extend({}, this, {
_id: undefined
}), cb);
};
resource.prototype.updateSafe = function (patch, cb) {
resource.get({id:this._id.$oid}, function(obj) {
for(var prop in patch) {
obj[prop] = patch[prop];
}
obj.update(cb);
});
};
resource.prototype.destroy = function (cb) {
return resource.remove({
id: this._id.$oid
}, cb);
};
return resource;
}
var dbUrl = "https://api.mongolab.com/api/1/databases/YOURDB/collections";
var apiKey = "YOUR API KEY";
var collections = [
"user",
"question",
"like"
];
for(var i = 0; i < collections.length; i++) {
var collectionName = collections[i];
app.factory(collectionName, ['$resource', function($resource) {
var resourceConstructor = createResource($resource, dbUrl, collectionName, apiKey);
var svc = new resourceConstructor();
// modify behavior if you want to override defaults
return svc;
}]);
}
app.controller('questionController', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What kind of AngularJS object should you create to contain data access or network communication logic?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('And, I got called back');
});
};
}]);
app.controller('questionController2', ['$scope', 'user', 'question', 'like',
function($scope, user, question, like) {
$scope.question = {
question: 'What is the coolest JS framework of them all?',
id: 1,
value: ''
};
$scope.save = function(obj) {
question.consoleLog(obj, function() {
console.log('You better have said AngularJS');
});
};
}]);
})();
In general, things related to the UI belong in a directive, things related to the binding of input and output (either from the user or from the server) belong in a controller, and things related to the business/application logic belong in a service (of some variety). I've found this separation leads to very clean code for my part.

Angular resource (ngResource) won't make the AJAX call when called inside a function

I'm trying to make an AJAX call with ngResource, In the code below 'a' and 'b' both print, but the AJAX call from Table.import() does not get made. If I move the AJAX call outside of onFileRead, then it works. What could be the problem?
var TableImportController = ['$scope','Table', 'project', 'table',
function($scope, Table, project, table) {
$scope.table = table;
$scope.project = project;
$scope.onFileRead = function(file) {
console.log('a');
Table.import({ data : file.data}, function() {
}, function() {
});
console.log('b');
};
}];
Where Table is an ngResource
.factory('Table', function($resource) {
var Table = $resource('/api/tables/:id:listAction/:itemAction',
{
id: '#id',
listAction: '#listAction',
itemAction: '#itemAction'
},
{
update: { method: 'PUT' },
import : { method: 'POST', params: { listAction: 'import' }},
}
);
return Table;
});
You are declaring $scope.onFileRead as a function.
What is calling onFileRead?
When you move the call outside of the function, it is being run as part of initialization.
What provides the input file?
Probably bind to the onFileRead function from something in your DOM.
I figured it out. It looks like I ran into this bug: https://github.com/angular/angular.js/issues/2794#issuecomment-18807158.
I solved the issue by wrapping the AJAX call (and eventually moved it to where the onFileRead callback is triggered) in a scope.$apply(function() { });

Resources