angular 不会对数组应用更改(删除套接字事件上的项目) [英] angular doesn't apply changes to array(remove item on socket event)

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

问题描述

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

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() 解决方案和安全应用(而 angular raise 正在进行异常),但没有任何效果.

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;
    });
  });
});

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

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆