Angular is built from ground up keeping separation of concern, modularity and testing in mind. One of the frequently asked question in AngularJS is where to use Directives and Services.
Directives
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM - (angularjs.org/guide/directive)
As mentioned in the definition, Directives are strictly for the DOM manipulation only. Directives are genius way to make DOM more intelligent e.g. we can create a directive which creates new element with node name as "tab" which angular at run time which resolve as HTML. This gives HTML a new meaning by creating new reusable tags and also gives us one code place to explain what tag "tab" are and easy to maintain.
Services
A service is any functionality which can be abstracted and then called by different functions e.g. $http, $routeProvider, etc. These services are needed to be injected in the controllers or other services using them to avoid direct reference to the functions. On injecting, these services are initialized and then can be used in the code without be directly object of the function. This is good code practice as we can mock the services for the test.
Ideally, directives should be strictly used for any UI view manipulation and services are abstracted functionalities which can be mocked for unit tests. Service should not be used for any DOM manipulation or event binding.
Directives
Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behavior, or transform the DOM - (angularjs.org/guide/directive)
As mentioned in the definition, Directives are strictly for the DOM manipulation only. Directives are genius way to make DOM more intelligent e.g. we can create a directive which creates new element with node name as "tab" which angular at run time which resolve as HTML. This gives HTML a new meaning by creating new reusable tags and also gives us one code place to explain what tag "tab" are and easy to maintain.
Services
A service is any functionality which can be abstracted and then called by different functions e.g. $http, $routeProvider, etc. These services are needed to be injected in the controllers or other services using them to avoid direct reference to the functions. On injecting, these services are initialized and then can be used in the code without be directly object of the function. This is good code practice as we can mock the services for the test.
Ideally, directives should be strictly used for any UI view manipulation and services are abstracted functionalities which can be mocked for unit tests. Service should not be used for any DOM manipulation or event binding.
No comments:
Post a Comment