Last active
August 29, 2015 14:07
-
-
Save shuhei/8447699e1f428a0f920a to your computer and use it in GitHub Desktop.
AngularJS: Sync service's data with controller
This file contains 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
'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; | |
}); |
This file contains 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> | |
<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