StackOverflow_25053704: angularjs-controlleras-register-destroy
Illustration of answer to http://stackoverflow.com/questions/25053704/angularjs-controlleras-register-destroy.
by ExpertSystem
HTML
<script src="http://code.angularjs.org/1.2.21/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.21/angular-route.min.js"></script>
<div ng-controller="mainCtrl">
<a href="#/">Home</a>
<a href="#/about">About</a>
<hr />
<div ng-view>Loading...</div>
</div>
<script type="text/ng-template" id="views/main.html">
<h1>{{ctrl.pageHeader}}</h1>
<p>{{ctrl.pageBody}}</p>
<hr />
<small>
This is just a dummy page, demonstrating how you can use a
<code>$scope</code> along with the <code>controllerAs</code> syntax.
</small>
</script>
<!-- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -->
<!-- Page Footer -->
<small class="footer" ng-controller="footerCtrl">
<b>Angular v{{version.full}}</b> ({{version.codeName}})
<span class="right">
© <a ng-href="{{authorUrl}}" target="_blank">ExpertSystem</a>
</span>
</small>
CSS
/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
body { padding-bottom: 22px; }
.footer { background-color: White; border-top: 1px solid rgba(100, 100, 100, 0.33); bottom: 0; display: block; font-size: 0.75em; height: 20px; left: 0; margin: 0 10px; overflow: auto; padding: 5px 0; position: fixed; right: 0; }
.right { float: right; }
JavaScript
var app = angular.module('myApp', ['ngRoute']);
app.controller('mainCtrl', function ($scope) {});
app.config(function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'views/main.html',
controllerAs: 'ctrl',
controller: function homeCtrl($scope) {
this.pageHeader = 'Home';
this.pageBody = 'Hey, it feels like home !';
$scope.$on('$destroy', function () {
alert('Let me clean up first !');
});
}
}).
when('/about', {
templateUrl: 'views/main.html',
controllerAs: 'ctrl',
controller: function aboutCtrl($scope) {
this.pageHeader = 'About Me';
this.pageBody = 'Yeah, what about me ?';
$scope.$on('$destroy', function () {
alert('Let me clean up first !');
});
}
}).
otherwise({redirectTo: '/'});
});
/* -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- -=-=-=-=- */
/* Page Footer */
app.controller('footerCtrl', function ($scope) {
$scope.authorUrl = '//stackoverflow.com/users/2341938/expertsystem';
$scope.version = angular.version;
});