简体   繁体   English

AngularJS:使服务状态可观察

[英]AngularJS: make service state observable

I have a directive for a filter object. 我有一个过滤器对象的指令。 The directive represents the filter as group of comboboxes. 该指令将过滤器表示为组合框组。 And I have a couple of another directives that should be affected by changes in the filter state (a list, for example). 我还有另外两个指令,这些指令应受过滤器状态(例如列表)的更改影响。 So when I change the value of a combobox in the filter it should update the property of the filter. 因此,当我在过滤器中更改组合框的值时,它应该更新过滤器的属性。 Then somehow other directives should be informed that filter has been changed and update accordingly after that. 然后应以某种方式通知其他指令过滤器已更改,并在此之后相应地进行更新。 For now I have a simple service for storing the filter state: 现在,我有一个简单的服务来存储过滤器状态:

angular.module("services", []).factory("svcFilter", function(){
    var filter = {};

    return filter;
});

This service is injected in the filter directive. 将该服务注入filter指令中。 When value of a combobox in the filter directive changed filter state changed: 当filter指令中的组合框的值更改时,过滤器状态也会更改:

angular.module("filter-module", ["services"])
    .directive("filter", function(){
        return {
            restrict: "E",
            templateUrl: "path/to/filter/template.html",
            controller: function($scope, svcFilter){
                ...
                $scope.$watch("filterProp1", function(newValue){
                    svcFilter["filterProp1"] = newValue;    
                });
            }
        }
    });

where filterProp1 is bound to the combobox value. 其中filterProp1绑定到组合框值。

So far so good. 到现在为止还挺好。 I can inject this service into other directives and they will be having the access to the filter state but will be never notified about its changes. 我可以将此服务注入其他指令,它们将可以访问过滤器状态,但永远不会收到有关其更改的通知。 How to solve it? 怎么解决呢? How to notify others about the changes? 如何将更改通知他人?

I worked off of @sss fiddle to amend it for isolate scope - fiddle 我用@sss小提琴来修改它以隔离范围- 小提琴

template: "<select ng-model='isolateProp1' ng-change='onChange()'>  <option value='volvo'>Volvo</option>  <option value='saab'>Saab</option>  </select> ",

controller: function ($scope, svcFilter) {
    $scope.svcfltr = svcFilter; // <-- this line seems to be making the difference

    $scope.$watch("svcfltr.filterProp1", function () {
        $scope.isolateProp1 = svcFilter.filterProp1;
    });

    $scope.onChange = function(){
        svcFilter.filterProp1 = $scope.isolateProp1;
    };
}

EDIT: 编辑:

Another approach is to directly assign a to-be-observed property of the service to a property of $scope : 另一种方法是将服务的待观察属性直接分配给$scope的属性:

$scope.isolateProp = svcFilter.filterProp;

Then, $scope.$watch is not even needed if you're using isolateProp as an expression in the view: {{isolateScope}} or ng-model="isolateScope" . 然后,如果您将isolateProp用作视图中的表达式: {{isolateScope}}ng-model="isolateScope" ,则甚至不需要$scope.$watch

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM