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.

2.2 KiB

Scope

Lesson Objectives

  1. Pass variables from controller to view using $scope
  2. Travel around the controller tree using $scope properties

Pass variables from controller to view using $scope

  • the glue between controllers and views
    • an object that gets properties added to it
    • each property turns into a variable in the view
      • just like res.render('view.ejs', {variable1:'foo'})

file: app.js

const app = angular.module('MyApp', []);

app.controller('BaseCtrl', ['$scope', function($scope){
	$scope.foo = 'bar';
}]);

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="BaseCtrl as base">
			<span ng-bind="foo"></span>
		</div>
	</body>
</html>

Travel around the controller tree using $scope properties

You can also access parent, child, and sibling controller properties via scope's `$parent`, `childHead`, `childTail`, `nextSbling`, `$prevSibling` properties

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 ng-controller="ParentCtrl as parent">
		<div ng-controller="ChildController as child1">
			<button ng-click="child1.getProps();">Click Me</button>
		</div>
		<div ng-controller="ChildController as child2">

		</div>
		<div ng-controller="ChildController as child3">

		</div>
	</body>
</html>

file: app.js

const app = angular.module('MyApp', []);

app.controller('ParentCtrl', ['$scope', function($scope){
	this.prop1 = 'foo';
}]);

app.controller('ChildController', ['$scope', function($scope){
	this.getProps = function(){
		console.log($scope.$parent); //get parent scope
		console.log($scope.$parent.parent.prop1); //get prop1 on controller instance
		console.log($scope.$parent.$$childHead); //get first child of parent
		console.log($scope.$parent.$$childHead.$$nextSibling); //get first sibling of first child of parent
	}
}]);