Skip to content

Instantly share code, notes, and snippets.

@shuhei
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/8447699e1f428a0f920a to your computer and use it in GitHub Desktop.
Save shuhei/8447699e1f428a0f920a to your computer and use it in GitHub Desktop.
AngularJS: Sync service's data with controller
'use strict';
angular.module('sync', [])
.controller('HomeController', function(Model, sync) {
this.toggleName = function() {
Model.toggleName();
};
sync(Model, 'getName', this, 'name');
sync(Model, 'theOther', this, 'other');
})
.service('Model', function($rootScope) {
var self = this;
var name = 'Shuhei';
this.getName = function() {
return name;
};
this.theOther = function() {
return name === 'Shuhei' ? 'Iehuhs' : 'Shuhei';
};
this.toggleName = function() {
name = name === 'Shuhei' ? 'Iehuhs' : 'Shuhei';
};
})
.factory('sync', function($rootScope) {
var scope = $rootScope.$new(true);
function sync(src, getter, dest, destProp) {
set();
scope.$watch(get, set);
function get() {
return src[getter]();
}
function set() {
dest[destProp] = src[getter]();
}
};
return sync;
});
<!DOCTYPE html>
<html>
<head>
</head>
<body ng-app="sync">
<div ng-controller="HomeController as home">
<h1>Hello, World!</h1>
<p>My name is {{home.name}}.</p>
<button ng-click="home.toggleName()">Rename as {{home.other}}</button>
</div>
<script src="./bower_components/angular/angular.js"></script>
<script src="./js/app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment