AngularJS : watching Service properties

自闭症网瘾萝莉.ら 提交于 2020-01-25 20:41:09

问题


Take the following plunk as an example:

http://plnkr.co/edit/vKFevXhhSprzFvesc6bG?p=preview

var app = angular.module('plunker', []);

app.service('SomeService', ['$rootScope', function ($rootScope) {
    var service = {
        value: false
    }

    return service;
}]);

app.controller('MainCtrl', ['$scope', 'SomeService', function($scope, SomeService) {
    $scope.value = SomeService.value;

    //$scope.$watch(function () { return SomeService.value; }, function (data) { $scope.value = data; });
}]);

app.controller('SecondaryCtrl', ['$scope', 'SomeService', function($scope, SomeService) {
    $scope.toggleValue = function () {
        SomeService.value = !SomeService.value;
    }
}]);

2 controllers and a service, 1 controller (SecondaryCtrl) updates a property on the service and the other controller (MainCtrl) references this property and displays it.

Note the $watch expression commented out in MainCtrl - with this line uncommented, everything works as expected but my question - is it necessary? Shouldn't the watch be implicit or am I doing something wrong?


回答1:


When you assign the value of SomeService.value to your scope variable, you are creating a copy of the variable which is a distinct object from the value inside SomeService. By adding the watch expression you were simply keeping the two variables (the one in the scope and the one in SomeService) synchronised.

The easiest way to go about this is not to copy the value, but create a reference to the service itself. So in MainCtrl

$scope.someService = SomeService;

and in your html

Value: {{someService.value}}

this way you are actually binding to the value inside SomeService.



来源:https://stackoverflow.com/questions/28872211/angularjs-watching-service-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!