What is the purpose of a return {...} block in AngularJS services? -


i'm starting learn basics of angularjs , looking @ example code:

'use strict';  angular.module('somemodule') .factory('dateformatter', function () {   var clean = function (date) {     return moment(date).format('yyyy-mm-dd');   };    return {     clean:clean   }; }); 

can tell me why necessary (or best practice, perhaps?) include return block @ bottom? make clean() function accessible external code or that?

thanks

by using factory method, pretty tell angularjs whenever object of dateformatter requested (for example, dependency injection mechanism), should execute method pass second parameter factory(..., ...), , supply object returned function rather function itself.

that is, angular not provide method define, object method returns. pretty word 'factory' refers to: 'create object me when ask it'.

if returned function, change have call function provides value/object, such this:

.controller(dateformatter) {   // if angular returned function rather it's returned value,   // have in order access clean function:   (dateformatter()).clean(); } 

in sense, assumption makes clean function accessible right. end, provides sort of encapsulation mechanism. if did this:

angular.module('somemodule') .factory('dateformatter', function () {   var clean = function (date) {     date = somehelperfunction(date);     return moment(date).format('yyyy-mm-dd');   };    var somehelperfunction(date) {     // here date   };    return {     clean:clean   }; }); 

then able call somehelperfunction function inside, not outside since not return it.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -