AngularJs : Struggling with scopes ?
Shaping up with AngularJs seems challenging to lot of people, I read blog posts and found people struggling with syntax and interpretation issues.
AngularJs is supported by Google hence we see people around us chatting about it. Nothing fancy and new but old coffee in new cup for those who understands JavaScript well. Using $scope might load your angular app with lots of listeners and events and cause performance issues. Each time a developer writes $scope, angular behind scene attached all necessary watches, listeners and events.
I’ve been reading lot of blog posts which recommends to avoid using scope in angular controllers for obvious reasons. Reasons which might leads to performance trouble when development is in middle. There are possible alternatives to avoid scope, which one is suitable for you and how that will help you to avoid performance roadblocks.
Alternatives for $scope
- Use ‘Controller As’ syntax
Using ‘Controller As’ syntax will let you access local controller variables to use with views and pass on data efficiently without any ‘mandatory’ watchers and listeners. This method will reduce usage of $scope, therefore $Apply cycle will reduce to speed up your angular molded application. Using this syntax will help you reduce annoying $digest errors and helps maintain cleaner code approach.
- Avoid watches using ‘ng-change’
Converting your $scope variables in ‘this’ might end up in trouble if you are explicitly using watches on controllers. If you’ve initiated watches in views to change models accordingly in controller then it might not fire change event and your ‘logic’ might stop working.
- Use ES5 or ES6 properties to build
Using ECMAScript 5 or ECMAScript 6 will help you modularize you code at some extent. Following this will also help you connecting you modules references easily. Usage of ‘import’ property is a plus in this case, old school way of writing JavaScript will unknowingly increase you LOC and might end up writing some thousands of lines in controllers itself.
There are several other ways to reduce usage of $scope in AngularJs application, I hope this article will help you decide the best and get rid of those slow applications. I would recommend to use these approach for large scale applications where controllers and services are present in hundreds
Specialist Software Engineer at NICE Ltd
9yGood one...
Senior Software Engineer
9yGood one ! Kunal sir