I heard that this service should not be bound to the scope variable in the controller, because the view gets direct access to the service. But I want to bind the scope variable to the data stored in the service, and I want this variable to reflect all changes from the service. I read a lot of workaround, and most of them were told to use $ scope. $ Watch, if I want to watch service data from the controller. I wrote a simple example without using $ scope. $ Watch, which works exactly the way I want, but I'm definitely not sure if I can use something like this, or this is bad practice. I have been studying angular for about 2-3 days and really need your advice:
HTML:
<div ng-controller="TestController">
<p>Current value = {{ serviceData.getValue() }}</p>
<input type="text" ng-model="newValue">
<button ng-click="changeServiceData(newValue)">Change</button>
</div>
module.js
var app = angular.module('app', []);
controller.js
app.controller('TestController', function($scope, testService){
$scope.serviceData = testService.getPublicData();
$scope.changeServiceData = function(newValue){
testService.setValue(newValue);
}
});
service.js
app.factory('testService', function(){
var value = null;
return {
setValue: function(newValue){
value = newValue;
},
getPublicData: function(){
return {
getValue: function(){
return value;
}
}
}
}
});
, . , , .
UPDATE:
factory :
app.factory('testService', function(){
var value = null;
return {
setValue: function(newValue){
value = newValue;
},
getValue: function(){
return value;
}
}
});
getter :
app.controller('TestController', function($scope, testService){
$scope.value = testService.getValue();
$scope.changeServiceData = function(newValue){
testService.setValue(newValue);
}
});
, setter, , . , ?