Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS Basics (1.x) Getting Started with Angular The Nuts And Bolts of Angular

Anthony c
Anthony c
20,907 Points

So, if we create a directive, we must also create a controller?

So, if we create a directive, we must also create a controller?

Or connect it to an existing controller?

In other words, we cannot create a custom directive without also having a corresponding controller for it?

1 Answer

akak
akak
29,445 Points

Well, that's hell of a question :) There are many ways controllers connects with directives. But at this point is's not about controller itself but controller's $scope and scope in general. I didn't take the course, hopefully Huston explains that a bit later ;)

But to answer your particular question - you can have directive that is not "connected" to any scope. It creates it's own scope and being fed by data from any source (usually model through controller but not only).

For example let's assume you have:

<div ng-repeat="item in data" red-vision>

So yes, this is brought by some controller but we don't care at this point which. At the end we have a custom directive (red-vision) added as an attribute.

Now let's write it:

.directive('redVision', function () {
    function link (scope, element, attrs) {
        element[0].style.color = 'red';
    }
    return {
        restrict: 'A',
        scope: {},
        link: link
    };
})

So what this does? It gets every single element that ng-repeat is outputting on the website and adds a css style making text color red. The scope: {} in return means that we're creating an isolated scope. We don't care how the data is fed to the directive - it does it job on every element given to it.

I know that it might make no sense at this point, but in some time you'll eventually get the scopes. I think I've read most of the stuff available online about that and still didn't get it until I've started to make my small angular test project.