Two-way binding between service and controller without $ scope. $ Watch. Is this a bad practice?

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, , . , ?

+4
1

, , , .

, getter setter:

app.controller('TestController', function($scope, testService){
  $scope.testService = testService;
  $scope.newValue    = 'initial-value';
});

HTML:

<div ng-controller="TestController">
  <p>Current value = {{ testService.getValue() }}</p>
  <input type="text" ng-model="newValue">
  <button ng-click="testService.setValue(newValue)">Change</button>
</div>

- , , , , .

ngModel , getter, :

<input ng-model="testService.value">

- , newValue, ngChange:

<input ng-model="newValue" ng-change="testService.setValue(newValue)">
+2

Source: https://habr.com/ru/post/1617330/


All Articles