Skip to content
JGefroh edited this page Aug 30, 2014 · 23 revisions

Writing Directives

  • If you're writing more than one $injector per application, you're doing it wrong.

  • $compile service traverses DOM, looks for all directives, and calls their compile function.

  • link function creates all the bindings.

  • Content flash can be avoided by using ngCloak.

  • There's an auto-translation between camel case in JS and HTML dash-separator (camelCase vs camel-case). HTML is case insensitive.

  • compile vs link

    • compile function doesn't have access to the scope, whereas link function does.
    • compile function gets executed once, whereas link function gets executed for every instance of a template.
    • compile function modifies template, link function does work of binding instance and template.
    • compile and link functions are remarkably similar until used in a repeater.
    • Use compile if modifying a template. Otherwise, use link.
  • Point of a directive is to be the glue between the DOM and the scope.

  • Events that occur in non-angular world do not propogate to the angular world.

    • $apply can be used as a gateway/bridge between the two.
  • Read out of scope using $watch.

  • Write to scope using $parse.

  • Making reusable components via directives:

    • Find and pull out common HTML code into own file.
    • Create a directive and point it to the HTML file via templateURL parameter.
    • Don't let your directives clobber other variables in the scope by restricting scope as necessary.
      • scope: false = no individual scope
      • scope: true = access to parent scope, but can set variables within own scope.
      • scope: {} = isolated scope, no access to outside except through parameters.
        • @ (Straight up string 'interpolation')
        • = (Modifiable attribute)
    • Nesting directives clobbers content.
    • If you want to avoid clobbering, use transclude: true.
    • Provide a location in the template for the transcluded content to reside via ngTransclude.
    • This will save whatever content is already in there.
    • Transcluded scope is not an isolate - its scope is the parent scope.
    • The scope of the directive can be a sibling scope.
  • Observations:

    • Application only has JS imports for categories/types (eg. directives, controllers, filters). Is it because the application is simple, or is this the actual way of importing things?
    • 'use strict' is the first line of the JS files. What is this for?
Clone this wiki locally