Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular controller communication via service
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="app">
<head>
<title>Demo</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Demo</h1>
<div class="row">
<div class="col-md-6" ng-controller="UserCtrl">
<fieldset>
<legend>User</legend>
<form name="address-form" novalidate>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" ng-model="user.Name" required ng-change="changed('Name', user.Name)" />
</div>
<div class="form-group">
<label>Email</label>
<input type="text" class="form-control" ng-model="user.Email" required ng-change="changed('Email', user.Email)" />
</div>
</form>
</fieldset>
</div>
<div class="col-md-6" ng-controller="InfoCtrl">
<fieldset>
<legend>Info</legend>
<dl>
<dt>
Name
</dt>
<dd>
{{user.Name}}
</dd>
</dl>
<dl>
<dt>
Email
</dt>
<dd>
{{user.Email}}
</dd>
</dl>
</fieldset>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
<script>
(function () {
"use strict";
var json = { "Name": "Tim", "Email": "tim@email.com" };
var app = angular.module("app", []);
app.value("json", json);
app.service("AppService", function ($rootScope) {
var svc = {
user: {},
update: function (prop, val) {
this.user[prop] = val;
$rootScope.$broadcast("updated");
console.debug("updated", prop, val);
},
getUser: function () {
return this.user;
}
};
return svc;
});
app.controller("UserCtrl", ["$scope", "AppService", "json", "$timeout", function ($scope, AppService, json, $timeout) {
$scope.user = {};
$scope.changed = function (prop, value) {
AppService.update(prop, value);
}
// Bootstrapping data
$timeout(function () {
console.debug("json", json);
$scope.user = json;
for (var item in json) {
$scope.changed(item, json[item]);
}
});
}]);
app.controller("InfoCtrl", ["$scope", "AppService", function ($scope, AppService) {
$scope.user = {};
$scope.$on("updated", function () {
var user = AppService.getUser();
console.debug("on updated", user);
$scope.user = user;
});
}]);
}());
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.