Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I guess you can roughly sum up what a directive is as "something that encapsulates a bunch of functionality into a widget that can be dropped into any page anywhere", but there's more to it than that. A directive is a way to extend HTML by creating new tags, allowing you to write more expressive markup. For instance, instead of writing a <code>&lt;div&gt;</code> and a bunch of <code>&lt;li&gt;</code> tags in order to create a rating control, you could wrap it up with a new <code>&lt;rating&gt;</code> tag. Or, instead of lots of <code>&lt;div&gt;</code>s, and <code>&lt;span&gt;</code>s and whatnot to create a tabbed interface, you could implement a pair of directives, say, <code>&lt;tab&gt;</code> and <code>&lt;tab-page&gt;</code>, and use them like this:</p> <pre><code>&lt;tab&gt; &lt;tab-page title="Tab 1"&gt; tab content goes here &lt;/tab-page&gt; &lt;tab-page title="Tab 2"&gt; tab content goes here &lt;/tab-page&gt; &lt;/tab&gt; </code></pre> <p>That's the truly power of directives, to enhance HTML. And that doesn't mean that you should only create "generic" directives; you can and should make components specific to your application. So, back to your question, you could implement a <code>&lt;loggedinuser&gt;</code> tag to display the name of the logged user without requiring a controller to provide it with the information. But you definitely shouldn't rely on a global variable for that. The Angular way to do it would be make use of a service to store that information, and inject it into the directive:</p> <pre><code>app.controller('MainCtrl', function($scope, userInfo) { $scope.logIn = function() { userInfo.logIn('Walter White'); }; $scope.logOut = function() { userInfo.logOut(); }; }); app.service('userInfo', function() { this.username = '' this.logIn = function(username) { this.username = username; }; this.logOut = function() { this.username = ''; }; }); app.directive('loggedinUser', function(userInfo) { return { restrict: 'E', scope: true, template: '&lt;h1&gt;{{ userInfo.username }}&lt;/h1&gt;', controller: function($scope) { $scope.userInfo = userInfo; } }; }); </code></pre> <p>Plunker <a href="http://plnkr.co/edit/yslizIzzaYM9Tsp8xX6Z?p=preview" rel="nofollow">here</a>.</p> <p>The <a href="http://docs.angularjs.org/guide/directive" rel="nofollow">Angular dev guide on directives</a> is a must-go place if you want to start creating powerful, reusable directives.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload