AngularJS Essentials
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Dependency Injection and Services<br />
return {<br />
plate: plate,<br />
color: color<br />
};<br />
}();<br />
Now, we are able to access the color but not the entrance of the car:<br />
> console.log(car.plate);<br />
6MB006<br />
> console.log(car.color);<br />
Blue<br />
> console.log(car.entrance);<br />
undefined<br />
Beyond that, we can apply another convention by prefixing the private members<br />
with _, making the code much easier to understand:<br />
var car = function () {<br />
var _plate = "6MBV006";<br />
var _color = "Blue";<br />
var _entrance = "2013-12-09T23:46:15.186Z ";<br />
return {<br />
plate: _plate,<br />
color: _color<br />
};<br />
}();<br />
This is much better than the old-school fashion implementation of the first example,<br />
don't you think? This approach could be used to declare any kind of <strong>AngularJS</strong><br />
component, such as services, controllers, filters, and directives.<br />
In the following code, we have created our parkingService using a factory function<br />
and the Revealing Module Pattern:<br />
services.js<br />
parking.factory("parkingService", function () {<br />
var _calculateTicket = function (car) {<br />
var departHour = new Date().getHours();<br />
var entranceHour = car.entrance.getHours();<br />
var parkingPeriod = departHour – entranceHour;<br />
var parkingPrice = parkingPeriod * 10;<br />
return {<br />
period: parkingPeriod,<br />
[ 72 ]<br />
www.it-ebooks.info