在嵌套函数调用中访问$ scope变量

时间:2015-04-21 15:02:24

标签: javascript angularjs

我有一个AngularJS应用程序使用Underscore.js进行一些过滤。我创建了一个自定义指令,它必须更新属于$ scope的数组的成员。在应用过滤器调整后,它调用$ scope函数将过滤器应用于结果。我现在的问题是从Underscore filter函数内部访问$ scope对象不会观察到绑定更新。这是指令:

app.directive('range', [function () {
    return {
        restrict: "A",
        scope: {
            top: "=top",
            bottom: "=bottom",
            isDisabled: "=disable",
            attid: "=attid",
            whenchanged: "&"
        },
        link: function(scope,elem,attrs) {
            jQuery(elem).each(function () {
                var el = jQuery(this);
                jQuery.ui.slider.prototype.widgetEventPrefix = 'slider';
                el.slider({
                    range: true,
                    disabled: scope.isDisabled,
                    min: scope.bottom,
                    max: scope.top,
                    values: [scope.bottom, scope.top],
                    orientation: "vertical",
                    slide: function (event, ui) {
                        jQuery("#" + scope.attid + "_label_top").val(ui.values[ 1 ]);
                        jQuery("#" + scope.attid + "_label_bottom").val(ui.values[ 0 ]);
                        scope.top = ui.values[ 1 ];
                        scope.bottom = ui.values[ 0 ];
                    },
                    stop: function (event, ui) {
                        scope.whenchanged();
                    }
                });
            });
        }
    };
}]);

这是使用指令的HTML:

<div range class="mps-slider" id="{{attribute.id}}" bottom="$parent.mpsfilters[attribute.id].range_bottom" top="$parent.mpsfilters[attribute.id].range_top" disable="$parent.mpsfilters[attribute.id].sliderDisabled" attid="attribute.id" ng-model="$parent.mpsfilters[attribute.id]" whenchanged="$parent.narrow()"></div>

注意:您在这里看到$ parent,因为这是在指令

这是控制器中的范围函数:

$scope.narrow = function () {
    console.log($scope.mpsfilters); // this line logs the values from my adjustments to the filter
    var filtered = _.filter(controller.parts, function (obj) {
        var result;
        for (var key in $scope.mpsfilters) {
            if ($scope.mpsfilters.hasOwnProperty(key)) {
                var keyname = key + '_search_value';
                var paKey = controller.findKey(obj.paValues, keyname);
                var paValue = obj.paValues[paKey][keyname];
                console.log($scope.mpsfilters[key]); // this logs the original values, not reflecting the adjustment
                result = (paValue >= $scope.mpsfilters[key].range_bottom && paValue <= $scope.mpsfilters[key].range_top);
            }
        }
        return result;
    });
    controller.parts = filtered;
    controller.filteredCount = filtered.length;
    $scope.$apply();
};

请参阅代码段中的注释以获取上下文。在Underscore过滤器调用之外记录数组反映了数据绑定,但不是来自内部。我无法弄清楚如何将$ scope变量传递给该函数,因为它是由Underscore预先定义的。

0 个答案:

没有答案