Created
October 6, 2014 14:41
-
-
Save alpavlove/8fc8e7552b489991f133 to your computer and use it in GitHub Desktop.
Controllers communicate to factory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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