角度ng-repeat不更新,当使用jQuery内部指令调用Angular 方法时

angular ng-repeat not updating, when angular method is called with jquery inside directive

本文关键字:指令 内部 调用 Angular 方法 jQuery ng-repeat 更新 角度      更新时间:2023-09-26

(第一次使用 Angular 的用户(

所以我尝试调用我创建的角度方法addField函数(如果我使用 ng-click 调用它,它会起作用(,当另一个元素使用 jqueryUI 可拖动和可拖放时。

拖放工作正常,它甚至可以正确更新我的模型,因为当我在控制台中运行$scope.fields时,当我在 addField 函数中中断时,它会找到我的对象。

问题是,尽管对象在那里,但它并没有像ng-click那样在ng-repeat html中显示它们。

angular.module('formApp', [])
    .controller('formController', ['$scope', function($scope) {
        $scope.fields = [
            //{label:'The Field Title, with Angular', desc:'Lorem Ipsum Dolor', req:false},
            //{label:'The Other Field Title, with Angular', desc:'Lorem Ipsum Dolor Dos', req:false}
            ];
        $scope.addField = function() {
            $scope.fields.push({label:'Added Form Title', desc:'Added Form Desc', req:true});
            //$scope.fieldLabel = '';
            console.log("addField");
        };
    }])
    .directive('drag', function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            $( elem ).draggable({
                helper: "clone",
                activeClass: "ui-state-default",
                hoverClass: "ui-state-hover",
                drop: function( event, ui ) {
                }
            });
        }
    }
    })
    .directive('drop', function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            $( elem ).droppable({
                hoverClass: "holder-state-highlight",
                drop: function(event, ui) {
                    //handleDropEvent(event, ui);
                    //sortOrder();
                    angular.element('#theForm').scope().addField();
                }
            });
        }
    }
});

发生这种情况是因为 jQuery drop 回调发生在 Angular 框架之外,所以 Angular 不知道它正在发生。 在这种情况下,您需要通过将 Angular 包装在 $apply 中来通知 Angular,如下所示:

.directive('drop', ['$scope', function($scope) {
return {
    restrict: "A",
    link: function(scope, elem, attrs) {
        $( elem ).droppable({
            hoverClass: "holder-state-highlight",
            drop: function(event, ui) {
                  //handleDropEvent(event, ui);
                  //sortOrder();
                  $scope.$apply(angular.element('#theForm').scope().addField());
                }
            });
        }
    }
}]);

您可以在此处阅读有关Angular $apply功能的更多信息。