使用angularjs查看新页面中的选定行详细信息

时间:2016-02-25 05:23:51

标签: javascript html angularjs

您好我想在下一页显示所选行值详细信息,我只在第一页显示名称和城市,其余字段将在点击按钮后查看。  我的html页面

 <!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<script src="detailCtrlr.js"></script>
</head>
<body ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr>
<td>Name</td>
<td>Age</td>
<td>details</td>
</tr>
<tr ng-repeat="x in names">
<td>{{x.Name}}</td>
<td>{{x.City}}</td>
<td><a href="#/viewdetail" type="submit"  name="viewdetails" ng-click="detail()">view</a></td>
</tr>
</table>
</body>
</html>

我的控制器是

   var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http) {
        $http.get("details.json").then(function(response) {
            $scope.names = response.data.records;
        });
$scope.detail=function(){
        //details code here
    }
    });

现在我正在获取此页面中的所有记录并显示正常,现在我想在详细信息页面中查看所选行的其他详细信息。

3 个答案:

答案 0 :(得分:1)

您可以使用本地存储查看所选行的所有数据。 请找到以下代码:

如果您获得每条记录的唯一ID,请尝试以下方法:

你的HTML会:<a href="#/viewdetail" type="submit" name="viewdetails" ng-click="detail(x.id)">view</a>

 var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http,$location,filter) {
        $http.get("details.json").then(function(response) {
            $scope.names = response.data.records;
        });

$scope.detail=function(SelectedRecordeid){

        var NameObj = $filter('filter')($scope.names, { id: SelectedRecordeid })[0];

        localStorage.setItem("NamesDetails",JSON.stringify(NameObj));

        $location.path('/viewdetail');
    }
    });

如果您没有获得每条记录的唯一ID,请尝试使用名称: 你的HTML会:<a href="#/viewdetail" type="submit" name="viewdetails" ng-click="detail(x.Name)">view</a>

 var app = angular.module('myApp', []);
    app.controller('customersCtrl', function($scope, $http,$location,filter) {
        $http.get("details.json").then(function(response) {
            $scope.names = response.data.records;
        });

$scope.detail=function(SelectedName){

        var NameObj = $filter('filter')($scope.names, { Name: SelectedName })[0];

        localStorage.setItem("NamesDetails",JSON.stringify(NameObj));

        $location.path('/viewdetail');
    }
    });

现在,在您的“viewdetail”页面的Controller用户下面,可以从本地存储中准备好数据。

var getAlldata = IsBlank(localStorage.NamesDetails) ? [] : JSON.parse(localStorage.NamesDetails);

您将获得“getAlldata”变量中的所有数据。

===================

您也可以使用以下方法在其他页面中获取数据。 在这种情况下,您必须调用两个单独的服务调用。 重写功能

$scope.detail=function(SelectedRecordeid){
                         window.location.hash = '#/viewdetail?id=' + SelectedRecordeid;
        }

现在在你的第二页使用下面的代码:

    function GetQueryString(key) {
    'use strict';
    var res,
        arrQueryStrings = window.location.hash.split("?"),
        queryStringCollection;

    if (arrQueryStrings[1] === undefined || arrQueryStrings[1] === null) {
        return null;
    }
    queryStringCollection = arrQueryStrings[1].split("&");
    $.each(queryStringCollection, function (index, value) {
        var queryStringName = value.split("=")[0];
        if (queryStringName === key) {
            res = value.split("=")[1];
        }
    });

    return res;
}

$scope.SelectedRecordeid = IsBlank(GetQueryString("id")) ? 0 : GetQueryString("id");

现在您在$ scope.SelectedRecordeid中拥有所选行的ID,因此您可以使用此ID调用服务并在第二页中获取完整详细信息。

答案 1 :(得分:1)

嗨我得到了我的问题的解决方案,我的控制器是

app.controller('homeController', function($scope, $http, $location,
         $rootScope, $filter, $window) {
    $http.get("app/components/shared/json/Patients.json").success(
            function(response) {
                $scope.emp = response.Employees

                    $scope.select = function(list) {
                    debugger;
                    //$rootScope.selected = list;
                    $scope.selected = list;
                    localStorage.setItem("NamesDetails", JSON
                            .stringify($scope.selected));
                    $location.path('/homeView')
                    console.log(list)
                }
                $scope.cart = JSON.parse(localStorage.getItem("NamesDetails"));
                console.log($scope.cart)

            })
})

和Html

<td> <a ng-click="select(list)">view</a></td>

答案 2 :(得分:0)

我知道我回答这个问题的时机不晚,但是对于那些仍然面临这个问题的人来说,这是我的代码,经过三天的努力寻找解决方案,该代码才有效。

我正在使用ng-resource显示详细信息。我有一个名为“ listfactory”的工厂。

// listFactory.js

angular.module(“ main”) .factory('listFactory',function($ resource){

Calling model(x) didn't return EagerTensor
Traceback (most recent call last):
    ...
    return loss_value, tape.gradient(loss_value, model.trainable_variables)
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/backprop.py", line 1042, in gradient
    flat_grad = imperative_grad.imperative_grad(
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/imperative_grad.py", line 71, in imperative_grad
    return pywrap_tfe.TFE_Py_TapeGradient(
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/eager/backprop.py", line 157, in _gradient_function
    return grad_fn(mock_op, *out_grads)
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_grad.py", line 252, in _MeanGrad
    sum_grad = _SumGrad(op, grad)[0]
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_grad.py", line 211, in _SumGrad
    output_shape_kept_dims = math_ops.reduced_shape(input_shape,
  File "/home/sfalk/miniconda3/envs/asr2/lib/python3.8/site-packages/tensorflow/python/ops/math_ops.py", line 3735, in reduced_shape
    input_shape = input_shape.numpy()
AttributeError: 'Tensor' object has no attribute 'numpy'

});

//控制器“ detailscontroller.js

.controller(“ detailsController”,function($ scope,$ http,$ routeParams,$ route,listFactory){

import numpy as np
import tensorflow as tf
from tensorflow.python.framework.ops import EagerTensor


class TimeReduction(tf.keras.layers.Layer):

    def __init__(self,
                 reduction_factor,
                 batch_size=None,
                 **kwargs):
        super(TimeReduction, self).__init__(**kwargs)
        self.reduction_factor = reduction_factor
        self.batch_size = batch_size

    def call(self, inputs):
        input_shape = tf.shape(inputs)
        batch_size = self.batch_size
        if batch_size is None:
            batch_size = input_shape[0]
        max_time = input_shape[1]
        num_units = inputs.get_shape().as_list()[-1]
        outputs = inputs
        paddings = [[0, 0], [0, tf.math.floormod(max_time, self.reduction_factor)], [0, 0]]
        outputs = tf.pad(outputs, paddings)
        return tf.reshape(outputs, (batch_size, -1, num_units * self.reduction_factor))


def make_encoder_model(
    input_shape: tuple,
    out_dim: int,
    num_layers: int,
    d_model: int,
    proj_size,
    initializer=None,
    dtype=tf.float32,
    stateful: bool = False,
    dropout=0.5,
    reduction_index=1,
    reduction_factor=2,
):
    def lstm_cell():
        return tf.compat.v1.nn.rnn_cell.LSTMCell(
            d_model,
            num_proj=proj_size,
            initializer=initializer,
            dtype=dtype
        )

    batch_size = None if not stateful else 1

    inputs = tf.keras.Input(
        shape=input_shape,
        batch_size=batch_size,
        dtype=tf.float32
    )

    x = tf.keras.layers.BatchNormalization()(inputs)

    for i in range(num_layers):
        rnn_layer = tf.keras.layers.RNN(lstm_cell(), return_sequences=True, stateful=stateful)
        x = rnn_layer(x)
        x = tf.keras.layers.Dropout(dropout)(x)
        x = tf.keras.layers.LayerNormalization(dtype=dtype)(x)
        if i == reduction_index:
            x = TimeReduction(reduction_factor, batch_size=batch_size)(x)

    outputs = tf.keras.layers.Dense(out_dim)(x)

    return tf.keras.Model(
        inputs=[inputs],
        outputs=[outputs],
        name='encoder'
    )


def gradient(model, loss, inputs, y_true):
    y_true = tf.transpose(y_true, perm=(0, 2, 1))
    with tf.GradientTape() as tape:
        y_pred = model(inputs, training=True)
        loss_value = loss(y_true=y_true, y_pred=y_pred)
        return loss_value, tape.gradient(loss_value, model.trainable_variables)


def main():
    X, Y = [
        np.random.rand(100, 512),
        np.random.rand(100, 512)
    ], [[[0]*50], [[1]*50]]
    # assert len(X) == len(Y)

    encoder_model = make_encoder_model(
        input_shape=(None, 512),
        out_dim=1,
        num_layers=2,
        d_model=10,
        proj_size=23,
        dropout=0.5,
        reduction_index=1,
        reduction_factor=2
    )

    enc_dataset = tf.data.Dataset.from_generator(
        lambda: zip(X, Y),
        output_types=(tf.float32, tf.int32),
        output_shapes=([None, 512], [None, None]),
    ).batch(2)

    loss = tf.keras.losses.MeanSquaredError()

    for x, y in enc_dataset:
        from_predict = encoder_model.predict(x)
        from_call = encoder_model(x)
        if not isinstance(from_predict, np.ndarray):
            print("Calling model.predict(x) didn't return np.ndarray")
        if not isinstance(from_call, EagerTensor):
            print("Calling model(x) didn't return EagerTensor")
        loss_value, gradients = gradient(encoder_model, loss, x, y)
        print(loss_value)
        print(gradients)

    print('All done.')


if __name__ == '__main__':
    main()

});

基本上,我正在遍历循环以检查routeparams是否与员工的电子邮件匹配。 希望这会有所帮助:)