如何停止从ng-if块中无限调用AngularJS函数?

时间:2018-12-27 00:00:30

标签: javascript html angularjs angularjs-scope infinite-loop

一个JS函数从HTML ng-if被无限次调用,并导致错误。

在我的HTML中,一行

<div ng-if="isCanvasAndFeatureFlagOrStoreTagSet(variant)"> 在下面调用一个角度函数:

$scope.isCanvasAndFeatureFlagOrStoreTagSet = (variant) => {
            if (variant.productCategory.productGroup === 'CANVAS_PRINTS') {
                const featureFlagName = 'MULTICOLOR_CANVAS';
                var featureFlagSet = false;
                return resourceExec({
                    resource: Features.getFeature({featureName: featureFlagName}),
                    success: (response) => {
                        if (response && response.name === featureFlagName && response.enabled) {
                            featureFlagSet = true;
                        }
                    },
                    failure: (fail) => {
                        featureFlagSet = false;
                    }
                });
                let storeTagSet = $scope.store.tags.indexOf("multicolorcanvas") != -1;
                return storeTagSet || featureFlagSet;
            } else {
                return false;
            }
        };

仅应在初始化期间进行一次检查,然后在页面上发生任何更改时进行一次检查。但是,在我的情况下,当对页面(添加产品)进行初始更改时,上述函数被调用了无数次,并在无数次以下产生了错误:

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: 
[[{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":{}}, 
{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":{}}], 
[{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."}, 
{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."}],[{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."},{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."}],[{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."},{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."}],[{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."},{"msg":"isCanvasAndFeatureFlagOrStoreTagSet(variant)","newVal":{},"oldVal":"..."}]]

如何避免像这样无限次调用此函数?

0 个答案:

没有答案