Skip to content

Instantly share code, notes, and snippets.

@alpavlove
Created October 6, 2014 14:41
Show Gist options
  • Save alpavlove/8fc8e7552b489991f133 to your computer and use it in GitHub Desktop.
Save alpavlove/8fc8e7552b489991f133 to your computer and use it in GitHub Desktop.
Controllers communicate to factory
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div>
<header ng-controller="HeaderCtrl">
<div ng-bind="getSharedVariable()"></div>
</header>
<div ng-controller="BodyCtrl">
<form ng-submit="setSharedVariable()">
<input type="text" ng-model="myVariable" />
<button type="submit">Submit</button>
</form>
</div>
</div>
</body>
</html>
angular.module('myApp', [])
.factory('MyFactory', function ($q) {
var mySharedVariable;
return {
setVariable: function (data) {
var deferred = $q.defer();
mySharedVariable = data;
deferred.resolve('success');
return deferred.promise;
},
getVariable: function () {
return mySharedVariable;
}
};
})
.controller('BodyCtrl', function ($scope, MyFactory) {
$scope.setSharedVariable = function () {
MyFactory.setVariable($scope.myVariable)
.then(function () {
$scope.myVariable = '';
})
}
})
.controller('HeaderCtrl', function ($scope, MyFactory) {
$scope.getSharedVariable = function () {
return MyFactory.getVariable();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment