Angular JS Best Practice

Angular JS Best PracticeThere are some tips for Angular JS coding.1. Avoid putting too many things on the scope.Angular constantly checks the ‘dirty check’ to see if anything changed in the scope.Use scope only when you need to pass data between the view & controller or modal.Just put exactly what will be displayed on the UI on the scope, and leave the rest as variables in the controller, but not on the scope.Every item added to scope adds a $watch to the item that listens for changes and updates/renders them between the controller and view.2. Avoid global variables.Avoid using global variables is very important because, being a single page app, the Garbage Collector will never trigger to clear global variables.3. Don’t do DOM manipulation in controllers.Don’t do DOM manipulation in controllers, as well as in services.Try to restrict that type of work to Directives.If you are doing DOM manipulation in controllers.
STOP NOW! You are doing something wrong.4. communication between controllers using service or fire events.If you need to communicate between controllers.There are two simple options.Either fire events ($broadcasts/$on) on the scope or create a Service (which is singleton).Don’t create your own new way outside of these two options.5. Always use the square bracket [] notation for listing your dependencies.Angular JS uses parameter names to inject the values to the controller function.In JavaScript minification process, these parameters are renamed to shorter strings.By which parameters are injected to the function with a string array, Angular JS can still inject the right values when the parameters are renamed.Use the [] notation for listing your dependencies.angularApp.controller([‘$scope’, function($scope) …instead ofangularApp.controller(function($scope)…Since Angular infers the controller’s dependencies from the names of arguments to the controller’s constructor function, if you were to minify the JavaScript code for [the] PhoneListCtrl controller, all of its function arguments would be minified as well, and the dependency injector would not be able to identify services correctly.

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *