Skip to content

Instantly share code, notes, and snippets.

@asicfr
Created May 6, 2013 12:07
Show Gist options
  • Save asicfr/5524756 to your computer and use it in GitHub Desktop.
Save asicfr/5524756 to your computer and use it in GitHub Desktop.
app.service('myService', ['$http', '$rootScope', function ($http, $rootScope) {
// data private access
var inData = {
cpt: 0,
mytext: 'hello who ?',
extData: undefined
};
var loadData = function () {
console.log("loadData");
var data = {
"hello": 'world'
};
return $http.post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
};
// data public access with getter setter
this.outData = {
get extData() {
console.log("get extData");
if (!inData.extData) {
inData.extData = "loading ..."; // init to avoid loop loading
var myPromise = loadData();
myPromise.then(function (response) {
console.log("myPromise success");
inData.extData = response.data;
$rootScope.$$phase || $rootScope.$apply();
}, function (response) {
console.log("myPromise error");
inData.extData = "error";
$rootScope.$$phase || $rootScope.$apply();
});
}
return inData.extData;
},
get cpt() {
console.log("get cpt");
return inData.cpt;
},
get text() {
console.log("get text");
return inData.mytext;
},
set text(val) {
console.log("set text");
inData.cpt = inData.cpt + 1;
inData.mytext = val;
}
};
this.showData = function () {
console.log('nb update ' + inData.cpt);
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment