本文介绍了角度不对数组应用更改(在套接字事件上删除项目)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,对不起我的英语,我是乌克兰语

First of all, sorry for my english, i'm ukrainian

执行socketio卡删除事件时,视图中没有任何改变

When socketio card delete event performed, there is nothing changed in view

我认为ng-repeat

ng-repeat in my view

<card object="item" ng-repeat="item in LOG"></card>

在我的控制器中

$scope.LOG = [{...},...{...}];

SocketIO发出

SocketIO emit

socket.on('card_was_deleted', function (data) {
    $scope.open_object = undefined;
    $scope.LOG = $scope.LOG.filter(function (obj) {
        return obj.ID != data.id;
    });
});//or var index = ...;$scope.LOG.splice(index, 1);

我一直在寻找$ scope.$ apply()解决方案并安全地应用(但在进行角度提升时例外),但没有任何效果.

I was looking for $scope.$apply() solutions and safe apply (while angular raise in progress exception), but nothing works.

请帮助.

将此代码包装为$ apply会引发"inprog"异常,因为我已经

wrapping this code into $apply raises "inprog" exception, because i have already

MyModule.factory('socket', function ($rootScope) {
var socket = io.connect(...);
var safeApply = function(scope, fn) {
  if (scope.$$phase) {
    fn();
  } else {
    scope.$apply(fn);
  }
};
return {
    on: function (eventName, callback) {
        socket.on(eventName, function () {
            var args = arguments;
            safeApply($rootScope, function () {
                callback.apply(socket, args);
            });
        });
    },
    emit: .../*same code with eventData */
};

});

我发现用ngRepeat中的纯html替换自定义受限元素可以正常工作.我的指令

i found that replacing custom restricted element with plain html in ngRepeat works fine.My directive

    .directive('card', function ($compile, $http, $templateCache) {
        return {
            restrict: 'E',
            replace: true,
            template: '',
            scope: { object: '=',
                collapseClick: '&',
 ...
            },
            link: function (scope, element, attrs) {
                var templateLoader = $http.get("/static/admin-panel/templates/card/card-" + (scope.object.type) + ".html", {cache: $templateCache});
                templateLoader.success(function (html) {
                    element.replaceWith($compile(html)(scope));
                });

            }}
    }
);

怎么了?

推荐答案

您需要包装任何在正常角度流中未执行的角度相关代码,$scope.$apply函数,因此它看起来像:

You need to wrap any angular related code which is not executed in normal angular flow with$scope.$apply function, so it will look like:

socket.on('card_was_deleted', function (data) {
  $scope.$apply(function(){
    $scope.open_object = undefined;
    $scope.LOG = $scope.LOG.filter(function (obj) {
       return obj.ID != data.id;
    });
  });
});

它将触发内部角度事件循环,您可以阅读有关它的更多信息这里.

It will trigger internal angular event loop, you can read more about it here.

这篇关于角度不对数组应用更改(在套接字事件上删除项目)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:46