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

AngularJS - Nesting, Services

Lesson Objectives

  1. Nest controllers within each other
  2. Use services to add functionality to controllers

Nest controllers within each other

  1. can have controllers nested within other controllers
  2. those inner controllers can access the properties of their parents
  3. useful for separating complex sections into smaller components
  4. Batarang
    • a chrome plugin that allows you to inspect the properties of controllers defined on elements
      1. add to Chrome and enable it
      2. Click on an element in the Chrome Dev tools
      3. There is now a $scope tab

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

  1. Services provide additional functionality to your controller

    • names always start with $
    • examples
      • $scope
        • handles how view receives data
      • $log
        • logging
      • $http
        • handles AJAX
  2. Need to be passed in as parameters of controller

    app.controller('SomeController', [ '$someService', function($someService){
    	$someService.doStuff();
    }]);
    
  3. Array syntax with $someService string avoids problems later on with minifying your code