Skip to content

Instantly share code, notes, and snippets.

@elisechant
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elisechant/5b0ed3c1b21719e49711 to your computer and use it in GitHub Desktop.
Save elisechant/5b0ed3c1b21719e49711 to your computer and use it in GitHub Desktop.
Angular parent-child controllers
angular.module('myApp', [
'ui.router'
]).config(function($stateProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/index.html'
})
.state('books', {
url: '/books',
templateUrl: 'views/books.html',
controller: 'BooksController',
controllerAs: 'books'
})
.state('book', {
url: '/book/:book_id',
templateUrl: 'views/book.html',
controller: 'BookController',
controllerAs: 'book'
})
;
});
<h1>Book</h1>
<h2>{{book.model.title}}</h2>
<h3>{{book.model.author}}</h3>
<p>{{book.propertyA}}</p>
angular.module('myApp').controller('BookController', function($http, $stateParams) {
var self = this;
self.model = {};
if (!_.isEmpty($stateParams)) {
$http.get('./data/book.' + $stateParams.book_id + '.json').then(function(resp) {
self.model = resp.data.books
});
}
self.propertyA = 'I am a property of BookController';
});
BOOKS
<br>
<ul>
<li
ng-repeat="book in books.model"
ng-controller="BookController as controller"
>
{{controller.propertyA}} <a ui-sref="book({ book_id: book.id })">{{book.title}}</a></li>
</ul>
angular.module('myApp').controller('BooksController', function($http) {
var self = this;
self.model = [];
$http.get('./data/books.json').then(function(resp) {
self.model = resp.data.books;
});
});
<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
<meta charset="UTF-8">
<title></title>
<base href="/" />
<script src="./node_modules/angular/angular.js"></script>
<script src="./node_modules/angular-ui-router/release/angular-ui-router.js"></script>
<script src="./node_modules/underscore/underscore.js"></script>
<script src="app.js"></script>
<script src="book/books_controller.js"></script>
<script src="book/book_controller.js"></script>
</head>
<body>
<ul>
<li><a ui-sref="home">Home</a></li>
<li><a ui-sref="books">Books</a></li>
<li><a ui-sref="book({ book_id: 1 })">Book 1</a></li>
</ul>
<div ui-view></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment