Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Build Your Own ng-controller Directive


    Have you ever wanted to write your own ng-controller directive? No?! That probably means you're sane. That said, it is an interesting study to lift the lid on the black box, and understand how your tools work on a more intimate level.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: The directive we probably take the most for granted is ng-controller. We use it everywhere, it's in all the demos, but some of us don't know what it's actually doing. Let's go ahead and write our own ng-controller directive.

    I set up a directive. Instead of ng-controller, we'll call it custom-controller. I'm going to return something that says scope True.

    Now, this is not an isolate scope. This would be an isolate scope. This just means create a new scope. If we have two controllers next to each other like this first control and the second control, like they are here, there is a new scope created for each one, and they don't have to conflict if they're the same scope.

    The other thing we're going to do is say controller -- you can assign a controller to a directive -- and the controller is going to be the at sign.

    There's a special scenario here. If you assign a controller to the at sign, in the Angular source, you can see it assigns the controller to the attributes and the name of the directive, meaning that it will look up the name of the directive, like ng-controller, and then pass in this stuff as what the controller should accept. That's pretty straightforward.

    From here, if I replace ng-controller with custom-controller and hit Replace All, you can see it's all there. When I refresh, everything works the same, so I've actually recreated it. If I look at the source for it, you can see that the ng-controller directive has a scope of True, a controller of @, and the last thing being a priority of 500. You can see that here.

    The default priority for any directive is zero, so putting the controller at a priority of 500 gives it a chance to run before other defaults, or gives it a chance for other directives to run before it if you were to put the priority higher. If I wanted to recreate it here, I could say priority 500.

    Now I have custom controller directive that duplicates the functionality of ng-controller.