【问题标题】:AngularJS Array Building and FilteringAngularJS 数组构建和过滤
【发布时间】:2016-03-18 18:29:33
【问题描述】:

所以在 AngularJS 中,我从我们的供应商那里得到了一个完整的前端,条件是他们不必支持它。不是做生意的最佳方式,但嘿,它是免费的,并且可以满足我的需求。话虽如此。在这个应用程序中,它通过 websocket 显示一大堆数据。工厂的所有复杂性以及其他任何事情都归结为这一点。一个数组对象,然后通过几个 ng-repeats 在 HTML 中引用。

这是对象:

var state = 
{   queues:[],
    representatives:[],
    representative_queues:[],
    customer_clients:[],
    support_sessions:[],
    representative_support_sessions:[],
    support_session_attributes:[],
    support_session_skills:[]
};

它通过这样的表格显示:

<table class="table table-condensed table-striped">
    <thead>
        <tr>
            <th>Table Id</th>
            <th>Username</th>
            <th>User Id</th>
            <th>Available</th>
            <th>Skills</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="rep in state.representatives">
            <td>{{rep.id}}</td>
            <td>{{rep.username}}</td>
            <td>{{rep.user_id}}</td>
            <td>{{rep.routing_available}}</td>
            <td>{{rep.skill_code_names}}</td>
        </tr>
    </tbody>
</table>

我需要做的是提取相互关联的各种项目,因为这些数组的构建非常类似于数据库模式,其中 rep.user_id 可能与另一个 array.item 相关联,例如主键。作为一个措辞示例,获取每个 rep.user_id 并循环遍历每个 session.user_id 进行匹配,如果匹配 pull session.session_key ... 然后匹配 sessionDetails.session_key 中的 session.session_key,如果匹配则回显会话中的所有项目.Details...等等,等等...遍历每个数组并根据匹配的主键选择您的数据。

由于一切都已经构建好了,我希望我可以使用一些过滤器或 ng-if 结构来处理所有这些,但坦率地说,我是 AngularJS 的新手,虽然我知道多种语言,但事实证明这非常困难。

任何帮助都将不胜感激,如果需要,我可以发布其他代码。

更新:这里有 2 个文件将所有数据解析和规范化驱动到状态表中。我认为复杂性问题在于,由于 datautil.js 文件驱动状态表中的数据,我不能使用新函数来构建特定表,而是必须使用过滤器或其他东西?

dashboard.js

var dataUtil = require('./datautil.js');

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}

function startsWith (string, prefix) {
    return string.slice(0, prefix.length) == prefix;
}

/*
 * Public members
 */
module.exports = {
    init: function(express, app, http, WebSocket, inIo) {
        socket = new WebSocket('');
        var handShaken = false;
        io = inIo;

        socket.on('open', function open() {
            console.log('socket is open...');
            socket.send('\ningredi state api\n');
        });

        socket.on('message', function(data, flags) {
            //console.log('received message...');
            var strData = String.fromCharCode.apply(null, new Uint16Array(data));
            console.log('---------------------------');
            console.log(strData);
            console.log('---------------------------');

            // we have to handle cases where partial results are sent
            if (endsWith(strData,'\n')) {
                if (partialResult.length > 0) {
                    strData = partialResult + strData;
                }

                // reset partial data
                partialResult = '';
            } else {
                // append to partial result
                partialResult += strData;
                return;
            }

            var result = null;
            var handler = null;

            if (!handShaken) {
              handler = authenticate;
              handShaken = true;
            } else {
              result = JSON.parse(fixBadJson(strData));
              handler = handlers[result[0].type];
            }

            handler(result);
        });

        io.on('connection', function(socket){
            io.to(socket.id).emit('model update', {'message':'Weclome to the real-time API monitoring app'});
            socket.broadcast.emit('model update', {'message':'A user is viewing the real-time API monitoring app'})
            updateState(null, true);
            socket.on('disconnect', function(){
                io.emit('model update', {'message':'A user stopped viewing the realtime API monitoring app'});
            });
        });
    }
};

/**
 * Private members
 */
var partialResult = '';
var socket = null;
var io = null;

var state = 
{   queues:[],
    representatives:[],
    representative_queues:[],
    customer_clients:[],
    support_sessions:[],
    representative_support_sessions:[],
    support_session_attributes:[],
    support_session_skills:[]
};

var authenticate = function() {
    console.log('authenticating...');
    var msg = {
      'type' : 'authenticate',
      'credentials' : {
        'username' : 'reporting',
        'password' : ''
      }
    };
    socket.send(JSON.stringify(msg)+'\n');
};

var onauthenticated = function(result) {
    console.log('authenticated...');
    subscribe(result);
};

var subscribe = function() {
    console.log('subscribing...');
    var msg = {
      'type' : 'subscribe',
      'tables' : 'all'
    };
    socket.send(JSON.stringify(msg)+'\n');
};

var onsubscribed = function(result) {
    console.log('subscribed...');
    updateState(result, true);
};

var onmodelupdate = function(result) {
    updateState(result, true);
};

var onmodeltruncate = function() {
    state = {
        queues:[],
        representatives:[],
        representative_queues:[],
        customer_clients:[],
        support_sessions:[],
        representative_support_sessions:[],
        support_session_attributes:[],
        support_session_skills:[]
    };  
};

var updateState = function(result, sendToClient) {
  if (result != null && typeof result != 'undefined') {
    dataUtil.parseResult(result, state, io);
  }

  if (sendToClient) {
    io.emit('state change', state);
  }
};

var fixBadJson = function(json) {
  var retVal = '[' + json.trim().split('\n').join(',') + ']';
  return retVal;
};

var handlers = {
    'authenticate_response':onauthenticated,
    'subscribe_response':onsubscribed,
    'model_update':onmodelupdate,
    'model_truncate':onmodeltruncate
};

datautil.js

/*
 * Public members
 */
module.exports = {
    parseResult: function(result,state,io) {
        if (typeof result == 'undefined' || result ==  null) {
            return;
        }
        for (var i=0; i<result.length; i++) {
            var obj = result[i];

            for (var type in obj) {/* type is like insert, update, delete */
                if (type == 'type') {
                    continue;
                }
                for (var table in obj[type]) { /* table are the table names */
                    var handlerType = type + '_' + table;
                    handler = updaters[type]; /* runs the corresponding function by associating the updaters obj to 3 functions like updaters[insert]= insertTable() */
                    handler(obj[type][table],state,io,type,table);

                    io.emit('model update', {'message':'Received... ' + handlerType});
                }
            }       
        }
    }
};

var insertTable = function(obj,state,io,type,table) {
    //console.log('inserting ' + table + '...');
    var tablePlural = table + 's';
    for (var item in obj) {
        var itemExists = false;
        for (var i=0; i<state[tablePlural].length; i++) {
            var tableItem = state[tablePlural][i];
            if (tableItem.id == item) {
                itemExists = true;
                break;
            }
        }
        if (!itemExists) {
            var tableObj = {};
            for (var field in obj[item]) {
                tableObj[field] = obj[item][field];
            }
            tableObj.id = item;
            state[tablePlural].push(tableObj);
        }
    }
};

var updateTable = function(obj,state,io,type,table) {
    console.log('updating ' + table + '...');
    var tablePlural = table + 's';
    for (var item in obj) {
        for (var i=0; i<state[tablePlural].length; i++) {
            var tableItem = state[tablePlural][i];
            if (tableItem.id == item) {
                for (var field in obj[item]) {
                    if (obj[item][field] != null && typeof obj[item][field] != 'undefined') {
                        //state[tablePlural][i][field] = obj[item][field];
                        tableItem[field] = obj[item][field];
                    }
                }
                break;
            }
        }
    }

};

var deleteTable = function(obj,state,io,type,table) {
    console.log('deleting ' + table + '...');
    var tablePlural = table + 's';
    for (var x=0; x<obj.length; x++) {
        var item = obj[x];
        for (var i=0; i<state[tablePlural].length; i++) {
            var tableItem = state[tablePlural][i];
            if (tableItem.id == item) {
                state[tablePlural].splice(i,1);
                break;
            }
        }
    }
};

var updaters = {
    'insert':insertTable,
    'update':updateTable,
    'delete':deleteTable
};

【问题讨论】:

    标签: arrays angularjs filter


    【解决方案1】:

    所以你想要的是这样的: (示例)

    if rep.user_id == session.user_id then
       pull session.session_key
          if session.session_key == sessionDetails.session_key
             pull session.Details object with properties
    

    还是我理解错了? 请给我您需要处理的正确信息(带有真实变量和属性),我会尝试给您一些有关如何操作的提示。

    【讨论】:

    • 您的示例是正确的。真正的问题是在没有 ng-repeat 的情况下进行迭代...或者我必须使用嵌套的 ng-repeat...我根本没有 Angular 背景来做这件事不过。
    • 好吧,我认为这是您想要管理的一般问题。我可以肯定地告诉你的一件事是不要考虑使用嵌套的 ng-repats,你可以在后端代码中做到这一点。这取决于您的架构是如何创建的。您可以在创建数据库时直接在项目之间建立这些关系,然后只检索包含对其他对象(父母或孩子)的引用的 1 个对象。这个呢?
    • 如何在后端使用一系列 foreach 循环来构建一个数组,然后只在前端引用新构建的数组?
    • 嗯,是的,你也可以这样做,但这取决于你将来是否容易理解。
    • 其实我从一开始就想告诉你,但我不知道你的代码是怎样的
    【解决方案2】:

    我在前端想通了。

        <div ng-repeat="support_session in state.support_sessions">
            <div ng-repeat="client in state.customer_clients">
                <div ng-if="client.support_session_id == support_session.id">
                    <div ng-repeat="rep_session in state.representative_support_sessions">
                        <div ng-if="rep_session.support_session_id == client.support_session_id">
                            <div ng-repeat="rep in state.representatives">
                                <div ng-if="rep.id == rep_session.representative_id" class="row" style="background-color: #f2f2f2;border-bottom: 1px solid black;">
                                    <div class="col-xs-6 col-sm-3" style="width:25%">{{rep.public_display_name}} ({{rep.username}})</div>
                                    <div class="col-xs-6 col-sm-3" style="width:25%;background-color: #ffffff">{{client.hostname}}</div>
                                    <div class="col-xs-6 col-sm-3" style="width:25%">{{support_session.customer_name}}</div>
                                    <div class="col-xs-6 col-sm-3" style="width:25%;background-color: #ffffff">{{client.operating_system}}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2016-08-18
      • 2016-10-03
      • 2018-01-28
      相关资源
      最近更新 更多