AngularJS:观察服务属性 [英] AngularJS : watching Service properties

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

问题描述

以下面的plunk为例:

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 个控制器和一个服务,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 中的值不同的对象.通过添加监视表达式,您只需保持两个变量(范围内的一个和 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 中

and in your html

Value: {{someService.value}}

通过这种方式,您实际上是绑定到 SomeService 中的值.

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

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

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