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.
1.8 KiB
1.8 KiB
AngularJS - Nesting, Services
Lesson Objectives
- Nest controllers within each other
- Use services to add functionality to controllers
Nest controllers within each other
- can have controllers nested within other controllers
- those inner controllers can access the properties of their parents
- useful for separating complex sections into smaller components
- Batarang
- a chrome plugin that allows you to inspect the properties of controllers defined on elements
- add to Chrome and enable it
- Click on an element in the Chrome Dev tools
- There is now a $scope tab
- a chrome plugin that allows you to inspect the properties of controllers defined on elements
file: index.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
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
-
Services provide additional functionality to your controller
- names always start with $
- examples
- $scope
- handles how view receives data
- $log
- logging
- $http
- handles AJAX
- $scope
-
Need to be passed in as parameters of controller
app.controller('SomeController', [ '$someService', function($someService){ $someService.doStuff(); }]); -
Array syntax with
$someServicestring avoids problems later on with minifying your code