I've been working on linking models to services in order to update global models throughout my app, but it doesn't seem to be functioning as expected.
Recently, I delved into AngularJS and I suspect that I may have misunderstood my code. From what I grasp, a service should function as an instance, unlike a factory singleton. This setup should enable me to utilize a service to manage all $scoped models.
I'm attempting to connect my model like this:
model: {{ language.title }}
>>> ctrl1: $scope.language = langSrvic.store;
>>> srvic: langSrvic.store = myFactory;
>>> ctrl2: langSrvic.set('locale', 'fr');
>>> language instance store updated (should reflect change in controller 1 model)
Here is a working example of my code on jsFiddle
//Angular Application
var app = angular.module('app',[]);
//Controller 1
app.controller('first', ['$scope', 'language', function($scope, language){
$scope.language = language.store;
setTimeout(function(){
console.log($scope.language.title); //My application
console.log(language.store.title); //Something something french
}, 1500);
}]);
//Language service
app.service('language', ['i18n', function(i18n){
return {
locale: 'en',
store: i18n['en'],
set: function(prop, val){
this[prop] = val;
this.store = i18n[this.locale];
}
}
}]);
//Factory - storing instead of an api temporarily
app.factory('i18n', [function(){
return {
en:{
title: 'My application'
},
fr:{
title: 'Something something french'
},
}
}]);
//Controller 2 - changing locale to fr which should update the instance store and so update the first scope
app.controller('second', ['$scope', 'language', function($scope, language){
language.set('locale', 'fr');
$scope.language = language.store;
}]);
<div ng-controller="first">
{{ language.title }}
<div ng-controller="second">
{{ language.title }}
</div>
</div>