【问题标题】:No update $scope in view after function函数后视图中没有更新 $scope
【发布时间】:2015-04-23 09:53:31
【问题描述】:

我的控制器中有一个名为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 是一个警报库。

【问题讨论】:

    标签: javascript arrays angularjs data-binding


    【解决方案1】:

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

    【讨论】:

    • 但是为什么现在还不醒呢?我的意思是,我所有的应用程序都使用this 进行数据绑定工作正常。 @oliveromahony
    • 可能是因为数据被填充,然后视图呈现。然后,当数据发生更改时,您需要以某种方式通知视图,而 this 变量没有这样做。您可以发布整个代码和 jsfiddle 之类的吗?
    • 也可以这样做 - 我更喜欢 $scope 方法,抱歉应该将其包含在我的原始答案中
    • 是的,我已经把答案放在下面了。感谢您的帮助@oliveromahony
    【解决方案2】:

    好的,我已经用 '$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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2021-12-05
      • 1970-01-01
      • 2017-04-27
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多