javascript - 显示来自数据库 AngularJS 的值

标签 javascript angularjs arduino

我是 Angular 的新手。我有一个项目,我和一个 friend 正在做这个项目,它充当“珊瑚礁坦克 Controller ”。它是一个 arduino/mysql 数据库/angularJS 页面。我的伙伴在前端工作,但由于工作不得不退学,现在我有一个半完成的网站。从后端的 Angular 来看,一切正常。在前端,我想添加一个部分来控制照明。我想从简单地显示存储在数据库中的每种 LED 颜色的值开始。我为每个要显示值的 LED 灯串创建了一个新 Controller :

'use strict';
/* Controllers */
angular.module('reefController.controllers', ['uiSlider'])
// Main Dashboard Controller
.controller('dashboardController', ['$scope', function($scope) {
   $.ajax({
        url: 'php/reef_controller_selectVals.php',
        type: 'json',
        success: function(data) {

            reefController.config.data = data;

            // Draw Charts

            $.each(data.charts, function(name, chartData) {

                $(chartData.series).each(function(idx, val){
                    // Reformat sensor names to their Human readable versions
                    this.name = reefController.labels[name].sensors[idx];
                });

                var options = $.extend(reefController.config.chartOptions, { 
                    chart: {
                        events: {
                            load: function() {
                                var chart = this;
                                setInterval(function() {                                    
                                    $.ajax({
                                    url: 'php/reef_controller_selectVals.php?incremental=' + chart.options.name,
                                    success: function(data) {  
                                        // Only add data points if the latest date in the DB is different
                                        if (!(chart.xAxis[0].dataMax == data.timestamp)) {
                                            $(chart.series).each(function(i, series) {
                                                series.addPoint([data.timestamp, data[series.options.id]], true, true);
                                            }); 
                                        } 
                                    }
                                });
                                }, reefController.config.timers.chartUpdateInterval);
                            }
                        },
                        renderTo: name
                    },
                    name: name,
                    series: chartData.series,
                    title: { text: reefController.labels[name].chart.title }
                });


                var chart = Highcharts.StockChart(options);
                reefController.config.charts[name] = chart;
            });

            //Set LED Value Labels



            // Set outlets
            var i = 0;
            $('.outlet').each(function(){
                if (!$(this).hasClass('constant')) {
                    $(this).attr('data-outlet-id', data.outlets[i].id)
                            .attr('data-reveal-id', 'date-time-modal')
                            .attr('data-on-time', data.outlets[i].on_time)
                            .attr('data-off-time', data.outlets[i].off_time);

                    if (data.outlets[i].active) {
                        $(this).addClass('active');
                    } else {
                        $(this).removeClass('active');
                    }
                    i++;
                    // Bind click event to outlets
                    $(this).click(function(){
                        var outlet = $(this);
                        var id = outlet.attr('data-outlet-id');
                        var newOutletState = (outlet.hasClass('active')) ? 0 : 1;

                        // Set datepickers to currently defined DB times
                        $('#on_time').val(outlet.attr('data-on-time'));
                        $('#off_time').val(outlet.attr('data-off-time'));

                        // Formatter function for date time pickers
                        var dateFormatter = function(elem, current_time) {
                            elem.html(moment(current_time).format('ddd M/D/YY HH:mm'));
                        };

                        $('#on_time').datetimepicker({
                            format: 'Y-d-m H:i:s',
                            inline: true,
                            defaultDate: outlet.attr('data-on-time'),
                            onChangeDateTime: function(current_time) { dateFormatter($('#on_time_display'), current_time) },
                            onGenerate: function(current_time) { dateFormatter($('#on_time_display'), current_time) }
                        });

                        $('#off_time').datetimepicker({
                            format: 'Y-d-m H:i:s',
                            inline: true,
                            defaultDate: outlet.attr('data-off-time'),
                            onChangeDateTime: function(current_time) { dateFormatter($('#off_time_display'), current_time) },
                            onGenerate: function(current_time) { dateFormatter($('#off_time_display'), current_time) }
                        });

                        // Submit Button
                        $('#submit-btn').click(function() {
                            data = {
                                'id': id,
                                'on_time': $('#on_time').val(),
                                'off_time': $('#off_time').val(),
                                'active': newOutletState
                            };

                            $.ajax("php/reef_controller_loadOutlet.php", {
                                type: 'POST',
                                data: data,
                                dataType: 'json',
                                success: function(data) {
                                    outlet.toggleClass('active');
                                }
                            });

                            $('#date-time-modal').foundation('reveal', 'close');
                        });
                        // Cancel Button
                        $('#cancel-btn').click(function(){
                            $('#date-time-modal').foundation('reveal', 'close');
                        });
                    });
                }
            });

        }
    });
}])

.controller('outletController', ['$scope', function($scope) {
    $.ajax({
        url: 'img/outlet.svg',
        success: function(svg) {
            var svgDoc = document.importNode(svg.documentElement, true);    
            $('.outlet').append(svgDoc);
        }
    });
}])
.controller('temperatureController', ['$scope', function($scope) { }])
    .controller('phController', ['$scope', function($scope) { }])

.controller('whiteLedCtrl', ['$scope', function($scope) {}])
.controller('blueLedCtrl', ['$scope', function($scope) {}])
.controller('variousColorLedCtrl', ['$scope', function($scope) {}]);

在我的 dashboard.html 文件中我有:

<table style="width: 100%;">
    <tr>
        <td>
            {{ ledValues }}
        </td>
    </tr>
    <tr>
        <td colspan="3" style="background: #eff4f6;"><input type="checkbox" name="overrideLightingSchema" value="overRide">
            &nbsp;&nbsp;Override Current Lighting Pattern
        </td>
    </tr>
    <tr>
        <td colspan="3">
            <select name="lightingSchemas">
                <option value="feedingLightingPattern">Feeding Schema</option>    
                <option value="morningLightingPattern">Morning Schema</option>
                <option value="standardLightingPattern">Standard Schema</option>
                <option value="twilightLightingPattern">Dusk Schema</option>
                <option value="nightTimeLightingPattern">Night Schema</option>
                <option value="deepNightLightingPattern">Late Night Schema</option>
            </select>
        </td>
    </tr>
</table>

有时这会显示数据库中的值,有时它只是说:

{{ ledValues }}

这可能是某种异步问题,但我的 Angular ,以及 JS 就此而言,很弱。任何帮助都会很棒。

最佳答案

我在这里看到的主要问题是您正在使用 $ajax 向服务器发出请求。

您使用来自服务器的响应来设置您的变量...

 reefController.config.data = data;

然而,由于 $ajax 不是 Angular 的一部分,所以这个更新发生在范围摘要之外。因此 Angular 不知道更新绑定(bind)。您可以尝试将您的作业包装在 $apply 中。

$scope.$apply(function(){
    reefController.config.data = data;
});

就是说,我看不到 reefController 的定义位置。您可能希望将其分配给范围:

$scope.$apply(function(){
    $scope.MyData = data;
});

但是,我实际上建议您将 $ajax 调用替换为 Angular $http 服务。

//inject $http
.controller('dashboardController', ['$scope', '$http', function($scope, $http) {

//then use it later on
$http({
  method: 'GET',
  url: 'php/reef_controller_selectVals.php'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
    $scope.MyData = data;

  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

示例

下面是一个如何使用 $http 从服务器获取数据的快速示例。

完整示例,包括虚假服务(不需要服务器响应)可在此处找到:http://codepen.io/anon/pen/GogWMV

'use strict';

angular.module('reefApp', [ 'uiSlider']); 

/* CONTROLLER */
angular.module('reefApp')
.controller('dashboardController', dashboardController);

  /* Define controller dependencies. 
  Note how we do not use $scope as we are using controller as vm syntax 
  And we assign our scope variables to 'ctrl' rather than scope directly.
  see john papa styleguide (https://github.com/johnpapa/angular-styleguide#style-y032)
  */
dashboardController.$inject = ['ledService'];

function dashboardController(ledService)
{
  var ctrl = this;

  //define an array to hold our led data
  ctrl.ledData = [];

  //call method to get the data
  getLedData();

  //this method uses our service to get data from the server
  //when the response is received it assigns it to our variable
  //this will in turn update the data on screen
  function getLedData()
  {
      ledService.getLedData()
      .then(function(response){
        ctrl.ledData = response.data;
      });
  }
}   

/* LED SERVICE */
/* the service is responsible for calling the server to get the data.
*/
angular.module('reefApp')
.factory('ledService', ledService);

ledService.$inject = ['$http'];

function ledService($http)
{
    var endpointUrl = "http://addressOfYourEndpoint";

    /* expose our API */
    var service =  {      
      getLedData: getLedData,      
    }
    return service;

   function getLedData()
   {
       /* this is how you would call the server to get your data using $http */     
       /* this will return a promise to the calling method (in the controller) 
          when the server returns data this will 'resolve' and you will have access to the data
          in the controller:
   Promises: http://andyshora.com/promises-angularjs-explained-as-cartoon.html*/
       return  $http.get(endpointUrl); 
   }
} 

更进一步,最佳实践是在服务内部保留对从服务器返回的数据的引用;一个原因是该服务是单例的 - 因此该数据服务及其数据可以跨 Controller 共享。

function ledService($http)
{
    var endpointUrl = "http://addressOfYourEndpoint";

    /* expose our API */
    var service =  {      
      ledData: [],
      getLedData: getLedData,      
    }
    return service;

   function getLedData()
   {
       return  $http.get(endpointUrl)
        .then(function(response)
        {
           /* assign response to service variable, before promise is returned to caller */
           service.ledData = response.data;
         }); 
   }
} 

然后在我们的 Controller 中...

  function getLedData()
  {
      ledService.getLedData()
      .then(function(response){
        ctrl.ledData = ledService.ledData;
      });
  }

更新

要收集更多数据,您可以为要收集的每条数据添加一个服务,或者为现有服务添加更多方法。假设您添加了一个 phService

然后将其注入(inject) Controller 。并添加调用一个新方法以将服务用于数据并分配给模型。然后它可以显示在 View 中。

dashboardController.$inject = ['ledService', 'phService'];

function dashboardController(ledService, phService)
{
  var ctrl = this;

  //our data will be stored here
  ctrl.ledData = [];
  ctrl.phData = [];

  //call methods to get the data
  getLedData();
  getPhData();

  function getLedData()
  {
      ledService.getLedData()
      .then(function(response){
        ctrl.ledData = response.data;
      });
  }

  function getPhData()
  {
      phService.getPhData()
      .then(function(response){
        ctrl.phData = response.data;
      });
  }
}  

然后在 View 中(HTML):

   <tr ng-repeat="ph in ctrl.phData">
        <td> PHValue</td>
        <td >
            {{ ph }}
        </td>
    </tr>

关于javascript - 显示来自数据库 AngularJS 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124229/

相关文章:

javascript - 使用 Angular.js 对 WordPress V2 API 进行基本 REST 调用

c++ - Arduino液晶显示屏: Generate a navigation menu by reading an array

c# - 通过 C♯ SQL 到 Arduino

javascript - grunt-html-build - 部分内的过程变量?

javascript - 从 ngRoute 迁移到 ui.router

javascript - slick carousel 在服务器上有 1px 高度,本地环境 100%

javascript - 使用 gulp connect 时 Bower 组件根目录

c++ - 如何使用#define 语句来设置字节数组?

javascript - Google map 绘图管理器在大头针掉落后启动绘图

javascript - GmailMessage 类正则表达式中的 Google Apps 脚本 getPlainBody() 不起作用