Angular service
Alternative to controllers inheritance
by Budhram Gurung
HTML
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-controller="BaseController">
<p>Base Controller Value: {{model.value}}</p>
<button ng-click="updateValue('Value updated from Base')">Update In Base</button>
<br>
<button ng-click="model.updateValue('Value updated from Base directly')">Update In Base directly</button>
<div ng-controller="DerivedController">
<p>Derived Controller Value: {{model.value}}</p>
<button ng-click="updateValue('Value updated from Derived')">Update In Derived</button>
<br>
<button ng-click="model.updateValue('Value updated from Derived directly')">Update In Derived directly</button>
</div>
</div>
JavaScript
var app = angular.module('myApp', []);
app.factory('sharedModel', function () {
var sharedModel = {
value: "Initial Value"
};
sharedModel.updateValue = function (value) {
sharedModel.value = value;
};
return sharedModel;
});
function BaseController($scope, sharedModel) {
$scope.model = sharedModel;
$scope.updateValue = sharedModel.updateValue;
}
function DerivedController($scope, sharedModel) {
$scope.model = sharedModel
$scope.updateValue = $scope.model.updateValue;
}