跨视图控制器传输值不起作用

时间:2014-07-25 04:15:27

标签: javascript html5 angularjs

在角度js应用程序中,我在main.html中定义了一个表格列作为可点击项目。点击后,它应该转到一个新的客户页面,将列单元格的值作为客户名称。我在main.js中为app模块定义了相应的服务。

客户页面视图接收所选/点击的客户的时间序列活动数据,并且应该为客户显示各种图表和表格。视图及其控制器代码也附加。还附加了REST API服务。

我希望当客户点击表格列单元格时,控件应转到main.js中相应服务下的setClientFromSelection() - 我在其中使用console.log打印客户端名称 - 它是不去那儿!

不确定我犯的是什么错误!任何指针都将非常感激。

main.html(相关代码):

<tr ng-repeat="data in clientdata track by data.attributes.client" ng-if="data.attributes.Status == statusColor">
<td><a ng-href="#customer" ng-click="setClientFromSelection(data.attributes.client)">{{data.attributes.client.split(".")[0]}}</a></td></tr>

main.js(相关代码):

'use strict';

angular.module('c3App')
    .controller('MainCtrl', ['$scope', 'ClientPerf', 'colorTransportService',
        function ($scope, ClientPerf, colorTransportService) {
            ClientPerf.get()
                .success(function(data) {
                    if (angular.isUndefined($scope.statusColor))  { $scope.statusColor = 'RED'; };
                    $scope.clientdata = data.payload.array;
                });

            $scope.$on('healthStatusClicked', function(e, color) {
                $scope.statusColor = angular.uppercase(color);
            });
    }])
    .service('clientTransportService', ['$rootScope', function($rootScope) {
        var client = '';

        var setClientFromSelection = function(clientName) {
            console.log("clientName: ", clientName);
            client = clientName;
            console.log("client: ", client);
            $rootScope.$broadcast('clientSelected', client);
        }

        var getSelectedClient = function() { return client; }

        return { 
            setClientFromSelection: setClientFromSelection, 
            getSelectedClient: getSelectedClient 
        };
    }])

clientDetails.html查看:

<div class="col-lg-6 text-center">
    <div class="panel panel-default" ng-style="{'width': '100%'}">
        <div class="panel-heading">
            <h3 class="panel-title">Usage<linechart data="dailyUsageData" options="dailyUsageOptions" mode=""></linechart></h3>
        </div>
        <div id="customer_activities_graph" ng-style="{'width': '97%'}"></div>
    </div>      
    <div class=" panel panel-default" ng-style="{'width': '100%'}">
        <div class="panel-heading">
            <h3 class="panel-title">{{client}} Timeline</h3>
        </div>
        <div id="container5" ng-style="{'width': '95%', 'margin-left': '2%'}"></div>
    </div>
</div>

customer.js控制器相关代码:

'use strict';

angular.module('c3App')
    .controller('CustomerCtrl', ['$scope', 'DailyUsage4Client', 'clientTransportService',
        function ($scope, DailyUsage4Client, clientTransportService) {
            $scope.dailyUsageData = [];
            $scope.dailyUsageOptions = {
                axes: {x: {type: "date", key: "x"}, y: {type: "linear"}},
                series: [
                    {
                      y: "value",
                      label: "Activity Count",
                      color: "#ff7f0e",
                      type: "column",
                      axis: "y"
                    }],
                tooltip: {
                    mode: "scrubber",
                    formatter: function (x, y, series) {
                          return moment(x).fromNow() + ' : ' + y;
                        }
                    },
                stacks: [],
                lineMode: "linear",
                tension: 0.7,
                drawLegend: true,
                drawDots: true,
                columnsHGap: 5
            };
            DailyUsage4Client.get()
                .success(function (data) {
                    if (angular.isUndefined($scope.client)) { $scope.client = 'servicemax.com'; };
                    var dailyUsage = data.payload.array;
                    for(var k = 0; k < dailyUsage.length; k++) {
                        $scope.dailyUsageData.push({
                            date: new Date(dailyUsage[k].attributes.dt.toString().replace(/(\d{4})(\d{2})(\d{2})/, "$2/$3/$1")),
                            value: dailyUsage[k].attributes.activities
                        });
                    };
                });

            $scope.$on('clientSelected', function(e, client) {
                $scope.client = client.split(".")[0];
            });
    }]);

为了完整起见,我将Rest调用定义如下:

angular.module('ClientServices', ['ngResource'])
    .config(function ($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
        $httpProvider.defaults.cache = false;
    })
    .factory("DailyUsage4Client", function($http, $rootScope) {
        return {
            get: function() { return $http.get('http://c3.captora.com/c3rests/c3/usageByDay/{{client}}'); }
        }
    });

3 个答案:

答案 0 :(得分:0)

clientTransportService是一个工厂(返回一个对象),但用作服务。尝试将其更改为工厂......

.factory('clientTransportService', ['$rootScope', function($rootScope) {

    // ...

    return { 
        setClientFromSelection: setClientFromSelection, 
        getSelectedClient: getSelectedClient 
    };
}])

或者将其修改为服务......

.service('clientTransportService', ['$rootScope', function($rootScope) {
    var client = '';

    this.setClientFromSelection = function(clientName) {
        console.log("clientName: ", clientName);
        client = clientName;
        console.log("client: ", client);
        $rootScope.$broadcast('clientSelected', client);
    }

    this.getSelectedClient = function() { return client; }
}])

控制器还需要将setClientFromSelection()添加到范围...

$scope.setClientFromSelection = clientTransportService.setClientFromSelection;

答案 1 :(得分:0)

clientTransportService更改为工厂,因为它正在返回一个对象。或者更改您的服务定义,使其成为Anthony Chu所回答的服务。

那是因为当您注入服务时,将为您提供服务定义中传递的函数的实例。

当您注入工厂时,将为您提供通过调用您在工厂定义中传递的函数返回的值。

请参阅service vs. factory vs. provider

上的完整答案

答案 2 :(得分:0)

如果不利用合适的路线计划,你会让自己的生活变得异常艰难。考虑在app.js文件中创建以下路线(或者在您配置主应用模块的任何地方):

$routeProvider.when('/customers/:customer_id', {
        templateUrl : '/views/customer.html',
        controller : 'CustomerCtrl'
});

因此,您只需链接到正确的客户ID即可。

在您的控制器中,您可以从$ routeParams中检索该ID,如下所示:

angular.module('yourApp').controller('OrganisationCtrl', function ($scope, $log, $window, $routeParams, $filter, kometContent, kometSystem, $location, $sce, $alert) {
    ($scope.getCustomer = function(id) {
        kometContent.customer(id).then(function (response) {
            $scope.customer = response;
        }, function (response) {
            $scope.$emit(kometSystem.error, 'Server error ' + response.status);
        });
    })($routeParams.customer_id);
});

请注意,我们通过$ routeParams将id传递给自运行匿名方法。这就是我们谈论代码约定时的意思。难道不是那么容易吗?现在,我们只需链接到&#39; / customers /:customer_id&#39; (例如,&#39; / customers / 17&#39;)没有任何特殊处理。