AngularJS:使服务状态可观察

时间:2014-10-15 16:06:44

标签: javascript angularjs observable

我有一个过滤器对象的指令。该指令将过滤器表示为组合框组。我还有一些其他指令应该受到过滤器状态变化的影响(例如,列表)。因此,当我更改过滤器中组合框的值时,它应该更新过滤器的属性。然后,不知何故应该通知其他指令过滤器已经更改并在此之后进行相应更新。现在我有一个简单的服务来存储过滤器状态:

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

    return filter;
});

此服务在filter指令中注入。当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;    
                });
            }
        }
    });

其中filterProp1绑定到组合框值。

到目前为止一切顺利。我可以将此服务注入到其他指令中,并且它们将具有对过滤器状态的访问权限,但不会通知其更改。怎么解决?如何通知其他人这些变化?

1 个答案:

答案 0 :(得分:1)

我使用@sss小提琴修改隔离范围 - fiddle

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;
    };
}

编辑:

另一种方法是直接将服务的待观察属性分配给$scope的属性:

$scope.isolateProp = svcFilter.filterProp;

然后,如果您在视图中使用$scope.$watch作为表达式,则甚至不需要isolateProp{{isolateScope}}ng-model="isolateScope"

相关问题