https://github.com/normandy72/controllers-inside-directives
Using Controllers Inside Directives. Coursera course "Single Page Web Applications with AngularJS" by Yaakov Chaikin.
https://github.com/normandy72/controllers-inside-directives
angular angularjs css css3 html html5 javascript js
Last synced: about 1 month ago
JSON representation
Using Controllers Inside Directives. Coursera course "Single Page Web Applications with AngularJS" by Yaakov Chaikin.
- Host: GitHub
- URL: https://github.com/normandy72/controllers-inside-directives
- Owner: Normandy72
- Created: 2023-01-10T14:58:27.000Z (over 3 years ago)
- Default Branch: master
- Last Pushed: 2023-01-10T16:11:18.000Z (over 3 years ago)
- Last Synced: 2025-01-14T12:46:53.608Z (over 1 year ago)
- Topics: angular, angularjs, css, css3, html, html5, javascript, js
- Language: JavaScript
- Homepage:
- Size: 66.4 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## Using Controllers Inside Directives
### Step 1: Declare Controller in Directive
```
function MyDirective(){
var ddo = {
scope: {
prop: '='
},
controller: ControllerFunction,
bindToController: true,
controllerAs: 'myCtrl',
templateUrl: "template.html"
};
return ddo;
}
```
`bindToController: true` - attach declared scope properties to controller instance instead of directly to $scope
`controllerAs: 'myCtrl'` - use 'myCtrl' in directive's template to refer to controller instance
### Step 2: Define Controller
```
ControllerFunction.$inject = ['Service'];
function ControllerFunction(Service){
var myCtrl = this;
myCtrl.method = function(){
var name = "Hello " + myCtrl.prop;
...
};
}
```
`var myCtrl = this;` - attach other properties to 'this' as usual
`myCtrl.prop` - use (& manipulate) props in isolate scope
### Step 3: Use In Directive's Template
```
{{myCtrl.prop}}
```
***
### One-way Binding
Watches only the identity of the parent property, not the property inside directive.
```
function MyDirective(){
var ddo = {
scope: {
prop: '<'
}
};
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 '='.
***