Trying to make a simple example with an AngularJS service.
I want to have some variables and functions in my data model ( service ) and through the controller, expose them and bind them to the view.
The problem is that the controller/view gets a new instance of the model somehow, and I can't really see how this is useful because I want to use other controllers/views to see the same data/API of the same service, not a new instance every time.
Here is an example on plunker : http://plnkr.co/edit/AKZLaT2HrkBPMkICsski?p=preview
/*****script.js******/
var app = angular.module('app', []);
app.service('myService', function() {
// my data here
var text = 'text',
text2 = 'text2';
// my function here
var copyText = function(){
console.log('BEFORE text: '+ text + ' text2: ' + text2);
text2 = text;
console.log('AFTER text: '+ text + ' text2: ' + text2);
};
// expose my variables/API here
return {
text: text,
text2: text2,
copyText: copyText
};
});
app.controller('myCtrl', [ '$scope', 'myService', function($scope, myService){
$scope.myService = myService;
}]);
/*****index.html******/
...
<div ng-controller="myCtrl">
<h1>angular service exposure</h1>
<input type="text" ng-model="myService.text">
<p>text: {{ myService.text }}</p>
<button ng-click="myService.copyText()">copy text to text2</button>
<p>text2: {{ myService.text2 }}</p>
</div>
if you open console, when you press the button you will see the 'real' values of the model, before and after the copying of text to text2. Which are not the ones I see in the view from the controller...