Created
November 11, 2015 16:46
-
-
Save highiq/fe9bae4c13e885a0be9a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| A few Angular Performance Tips & Best Practices to follow | |
| for big performance gains for Angular 1.x applications | |
| */ | |
| // #1 - AVOID WATCH EXPRESSIONS WHENEVER POSSIBLE | |
| // 1-A | |
| //Don't do this | |
| <input type="text" ng-model="name" /> | |
| app.controller('MyCtrl', function($scope){ | |
| $scope.$watch('name', function(){ | |
| //call some service here | |
| }); | |
| }); | |
| //Do this | |
| <input type="text" ng-model="ctrl.name" ng-change="ctrl.search(ctrl.name)" /> | |
| MyCtrl.prototype.search = function(name){ | |
| //call some service here | |
| }; | |
| // 1-B | |
| //Don't do this | |
| app.controller('MyCtrl', function($scope){ | |
| $scope.$watch('selectedItem', function(){ | |
| //call some service here | |
| }); | |
| }); | |
| //Do this instead | |
| var MyCtrl = function(){ | |
| this._selectedItem = null; | |
| }; | |
| Object.defineProperty(MyCtrl.prototype, | |
| "selectedItem", { | |
| get: function () { | |
| return this._selectedItem; | |
| }, | |
| set: function (newValue) { | |
| this._selectedItem = newValue; | |
| //Call method on update | |
| this.onSelectedItemChange(this._selectedItem); | |
| }, | |
| enumerable: true, | |
| configurable: true | |
| }); | |
| // #2 - AVOID SHARING DATA WITH CONTROLLER TO CONTROLLER | |
| // 2-A | |
| //Don't do this | |
| app.controller('Parent', function($scope){ | |
| var sharedObj = { | |
| someProperty: 'foo' | |
| }; | |
| $scope.sharedObj = sharedObj; | |
| $scope.$watch('sharedObj.someProperty', function(){ | |
| //call some service here | |
| }); | |
| }); | |
| app.controller("Child", function($scope){ | |
| $scope.$watch('sharedObj.name', function(){ | |
| $scope.myName = $scope.sharedObj.name; | |
| }); | |
| }); | |
| //Do this instead | |
| var Parent = function(sharedDataService){ | |
| sharedDataService.updateName('foo'); | |
| }; | |
| var Child = function(sharedDataService){ | |
| sharedDataService.onNameChanged(this.nameChangedHandler); | |
| }; | |
| Child.prototype.nameChangedHandler = function(){ | |
| this.myName = sharedDataService.getName(); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment