A collection of 6 of the best Angular JS Tips and Tricks
Thanks : Angularjs4u.com
Tips #1 : Link - href
If you want to use AngularJS markup inside your links, you have to use ng-href instead of href. The reason is that it takes time for AngularJS to parse all HTML, and this means that if the user is quick he/she can click the link before it is actually parsed. This would result in a 404-page. So, instead of writing this:<a href="http://www.someurl.com/{{hash}}"/>you should write this:
<a ng-href="http://www.someurl.com/{{hash}}"/>
Tips #2 : Image - Src
This is similar to using ng-href instead of href. Whenever you insert images and want to use Angular-markup, you have to use ng-src. Just like this:<ul id="preview" ng-repeat="image in images"> <li><img ng-src="{{image}}" /></li> </ul>
Tips #3 : How to check if form data changes or not
I needed to implement a functionality that would warn the user about changed data in a form when the user tried to navigate away from the form. Luckily, in AngularJS this is very easy. You just use the $dirty variable. Just like so:$scope.back = function($event, ConfirmBackText) { $event.preventDefault(); if ($scope.mainform.$dirty) { if (confirm(ConfirmBackText)) { window.history.back(); } } else { window.history.back(); } };Notice, that I check whether or not $scope.mainform.$dirty is true or false. If it is true, I pop the confirm dialogue.
Tips #4 : Two callback at once
AngularJS allows you to watch a variable and will call a callback whenever its content is modified. But what if you need to watch two variables at once? You can write this:function callback() { ... } $scope.$watch('a', callback); $scope.$watch('b', callback);But you can also write this, which is more elegant:
$scope.$watch('a + b', callback);The value of “a + b” will change whenever either a or b changes. Therefore you watch both variable at once.
Tips #5 : Syntax of directives
The tutorial of AngularJS writes directives like this: "ng-model". But you can also write: "x-ng-model", "ng:model", "ng_model", "data-ng-model". They are all equivalent and work the same. I like to use the syntax with "data-" because it is standard-compliant.Tips #6 : Nuances of ngDisabled
There is actually an ngDisabled attribute that you can leverage for dynamically changing the disabled state of a form control. However, there may still be some confusion as to the different states and values that represent disabled or enabled, so to help clarify I made this simple demo: http://jsfiddle.net/ProLoser/j4EkX/light/Thanks : Angularjs4u.com