AngularJS:监视服务属性 [英] AngularJS : watching Service properties

查看:76
本文介绍了AngularJS:监视服务属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下面的小插曲为例:

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个控制器和一个服务,其中1个控制器(SecondaryCtrl)更新服务上的属性,另一个控制器(MainCtrl)引用并显示该属性.

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.

请注意,在MainCtrl中注释了$ watch表达式-未注释此行,一切正常,但我的问题-是否有必要?手表不应该是隐性的,还是我做错了什么?

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?

推荐答案

将SomeService.value的值分配给作用域变量时,您正在创建变量的副本,该副本是与SomeService中的值不同的对象.通过添加watch表达式,您只需使两个变量(作用域中的一个和SomeService中的一个)保持同步.

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.

最简单的方法不是复制值,而是创建对服务本身的引用.所以在MainCtrl

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;

和您的html

Value: {{someService.value}}

这样,您实际上是绑定到SomeService中的值.

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

这篇关于AngularJS:监视服务属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆