You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
1.8 KiB
72 lines
1.8 KiB
# AngularJS - Nesting, Services
|
|
|
|
## Lesson Objectives
|
|
|
|
1. Nest controllers within each other
|
|
1. Use services to add functionality to controllers
|
|
|
|
## Nest controllers within each other
|
|
|
|
1. can have controllers nested within other controllers
|
|
1. those inner controllers can access the properties of their parents
|
|
1. useful for separating complex sections into smaller components
|
|
1. Batarang
|
|
- a chrome plugin that allows you to inspect the properties of controllers defined on elements
|
|
1. add to Chrome and enable it
|
|
1. Click on an element in the Chrome Dev tools
|
|
1. There is now a $scope tab
|
|
|
|
file: index.html
|
|
|
|
```html
|
|
<!DOCTYPE html>
|
|
<html ng-app="MyApp">
|
|
<head>
|
|
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
|
|
<script src="app.js" charset="utf-8"></script>
|
|
</head>
|
|
<body>
|
|
<div ng-controller="ParentController as parent">
|
|
<div ng-controller="ChildController as child">
|
|
<span>{{child.property1}}:{{parent.property1}}</span>
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>
|
|
```
|
|
|
|
file: app.js
|
|
|
|
```javascript
|
|
const app = angular.module('MyApp', []);
|
|
|
|
app.controller('ParentController', [function(){
|
|
this.property1 = 'fun';
|
|
}]);
|
|
|
|
app.controller('ChildController', [function(){
|
|
this.property1 = 'awesome';
|
|
}]);
|
|
```
|
|
|
|
## Use services to add functionality to controllers
|
|
|
|
1. Services provide additional functionality to your controller
|
|
- names always start with $
|
|
- examples
|
|
- $scope
|
|
- handles how view receives data
|
|
- $log
|
|
- logging
|
|
- $http
|
|
- handles AJAX
|
|
1. Need to be passed in as parameters of controller
|
|
|
|
```javascript
|
|
app.controller('SomeController', [ '$someService', function($someService){
|
|
$someService.doStuff();
|
|
}]);
|
|
```
|
|
|
|
1. Array syntax with `$someService` string avoids problems later on with minifying your code
|