Using Controllers
Inside Directives
Step 1: Declare Controller in Directive
function MyDirective() {
var ddo = {
scope: { A"ach declared scope
prop: '=', [Link] to controller
}, instance instead of
controller: ControllerFunction, directly to $scope
bindToController: true,
controllerAs: 'myCtrl',
templateUrl: '[Link]'
Use ‘myCtrl’ in [Link]’s
}; template to refer to
return ddo; controller instance
}
Step 2: Define Controller
ControllerFunction.$inject = ['Service'];
function ControllerFunction(Service) {
var myCtrl= this; A"ach other [Link]
to ‘this’ as usual
[Link] = function () {
var name = "Hello " + [Link];
…
};
} Use (& manipulate)
props in isolate scope
Step 3: Use In Directive’s Template
<div ng-if="[Link]()">
{{[Link]}}
</div>
Bi-Directional vs. One-way Binding
function MyDirective() {
var ddo = {
scope: {
prop: '=',
},
...
};
return ddo;
}
Bi-Directional vs. One-way Binding
function MyDirective() {
One-way binding:
var ddo = {
Watches only the [Link] of
scope: {
the parent property, not the
prop: '<', property inside [Link]
},
...
};
return ddo;
}
Summary
² To add functionality to the directive, one choice is to use a
controller that’s declared directly on the DDO
² Use controller property to declare controller in DDO
² Use bindToController and controllerAs props to bind declared
properties in isolate scope directly to controller instance
² Define controller function as usual
² Whenever possible, use ‘<‘ for one-way binding to save
resources instead of bidirectional binding with ‘=‘