Skip to content

Instantly share code, notes, and snippets.

@ttsvetko
Created September 25, 2018 07:03
Show Gist options
  • Save ttsvetko/6fb91bd7bc654846988bceae77b4c262 to your computer and use it in GitHub Desktop.
Save ttsvetko/6fb91bd7bc654846988bceae77b4c262 to your computer and use it in GitHub Desktop.
Angular Directives - Lesser Known

Lesser know AngularJS directives

Lesser know AngularJS directives

One of the most awesome things in angular is its approach towards creating reusable HTML attributes and elements through ‘Directives’. Along with letting you write your own custom directives, angular ships with a lot of default directives. While some are helpers like ng-show,ng-class others like ng-model and ng-src are bound with angular internals.

This blog post is a list of a few lesser known yet useful directives.

These along with many other built in angular directives give us a hint of what angular project philosophy is and where it is heading towards: Making Common UI events more declarative, reusable and decoupled from the application logic.

ng-if

From an aesthetic point ng-if works similar to ng-show and ng-hide, but instead of hiding the Dom element it selectively adds or removes it from the DOM tree based on whether the expression supplied it true for false. This is use full because unlike hide and show, the removed element will not be collected when using css selectors.

ng-class-even/ng-class-odd

While in ng-repeat, we can selectively add classes to the repeated element based on whether the index of the element is odd or even.

Bonus:$index gives the index of the element in the iterator.

ng-change

ng-change lets you to trigger a function or evaluate a expression when the text changes in the particular text box. For the ng-change to work, the text box should be binded to a model.

ng-dbclick

db-click handles double click events within an element and lets you invoke a function or evaluate a expression when it is done.

similar:ng-mousedown,ng-keypress.

ng-style

Lets you add inline styles to your elements. although inline styles are evil and should be avoided, this cool as you can dynamically update your style attribute values based on a model binding.

ng-pluralize

The pluralize directive lets you pluralize your content based on en-US localization rules.

Example

<span>
    {{group.members_count}}
    <ng-pluralize count='group.members_count'.when="{'1': 'Member','other':'Members'}">
</span>

Based on the value of members_count. member or members is rendered.

ng-cloak

When the browser renders HTML if AngularJS is not loaded completly, the bindings will show up as very ugly curly braces. This directive acts as blanket from displaying angular binding syntax before Angular JS is loaded into the browser. Using this directive in your main pages is a must.

similar:ng-href

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment