$ scope。$ apply throw exception ... $ scope.apply已在进行中

时间:2015-03-30 21:25:31

标签: angularjs angularjs-scope

我正在尝试根据我在摘要中间对我的$ scope变量所做的更改来更新我的视图。在对我的变量进行必要的更改后,我调用了$ scope。$ apply (),这实际上导致了一个异常,说$ scope。$ apply已经在进行中。有人可以帮我解决这个问题。

this.showCart = false;

/*This function is called from the view on a ng-click*/
this.addCart=function(){

        if (this.showCart === false) {
            this.showCart = true;
            this.hideEmptyCart = 'none';
            this.showFullCart = 'initial';
            this.searchRightMargin = 40;
            this.updateWidth();
            $scope.$apply();
        }
}

1 个答案:

答案 0 :(得分:0)

查看您的代码,您的问题可能与范围参考有关。函数外部的this引用的范围限定为控制器,而函数内的this引用的范围限定为该函数。尝试将所有内容更改为$scope

$scope.showCart = false;

/*This function is called from the view on a ng-click*/
$scope.addCart=function(){
    if ($scope.showCart === false) {
        $scope.showCart = true;
        $scope.hideEmptyCart = 'none';
        $scope.showFullCart = 'initial';
        $scope.searchRightMargin = 40;
        $scope.updateWidth();
    }
}

然后,从ng-click

调用您的函数
<button ng-click="addCart()">Add To Cart</button>

<强>更新

或者,您可以尝试将控件的引用保存为self

var self = this;
self.showCart = false;

/*This function is called from the view on a ng-click*/
self.addCart=function(){
    if (self.showCart === false) {
        self.showCart = true;
        self.hideEmptyCart = 'none';
        self.showFullCart = 'initial';
        self.searchRightMargin = 40;
        self.updateWidth();
    }
}