在函数之后没有更新$ scope

时间:2015-04-23 09:53:31

标签: javascript arrays angularjs data-binding

我的控制器中有一个名为this.selectedCourses的数组。这个数组有一些项目在我的视图中显示为列表。 经过一些步骤后,我有了这个:

this.checkAddedCourses = function(studentCourses){
        ...

        if(repeatedCourses.length != 0){
            sweetAlert({
                  title: title,
                  text: text + ' ' + courseList,
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: confirmButtonText,
                  closeOnConfirm: false,
                  html: true
                }, 
                function(){
                    angular.forEach(repeatedCourses, function(repeatedCourse){
                        this.removeCoursePurchase(repeatedCourse);
                    }.bind(this));
                    swal("Deleted!", "Your purchase has been refreshed.", "success");
            }.bind(this));
        }
    }

当用户点击“删除”按钮时,项目会从数组中删除,我已经检查过,但在我的视图中,我仍然看到这些项目,直到我对该数组执行某些操作。就像删除元素后没有刷新数组一样。

感谢。

PD:sweetAlert是一个警报库。

2 个答案:

答案 0 :(得分:1)

使用$ scope而不是this来对视图进行数据绑定 - 所以$ scope.selectedCourses。请记住将$ scope作为依赖项传递给控制器​​。

答案 1 :(得分:0)

好的,我已经使用'$ apply'功能解决了这个问题:

sweetAlert({
                  title: title,
                  text: text + ' ' + courseList,
                  type: "warning",
                  showCancelButton: true,
                  confirmButtonColor: "#DD6B55",
                  confirmButtonText: confirmButtonText,
                  closeOnConfirm: false,
                  html: true
                }, 
                function(){
                    angular.forEach(repeatedCourses, function(repeatedCourse){
                        $rootScope.$apply(function() {
                            this.removeCoursePurchase(repeatedCourse);
                        }.bind(this));
                    }.bind(this));
                    swal("Deleted!", "Your purchase has been refreshed.", "success");
            }.bind(this));
相关问题