显示来自数据库AngularJS的值

文尼·古塔拉(VinnyGuitara)

我是Angular的新手。我有一个朋友在做的项目,我当时正在做一个“礁石箱控制器”。这是一个arduino / mysql数据库/ angularJS页面。我的好友正在前端工作,但由于工作原因不得不退学,现在我的网站已经完成了一半。从后端的角度来看,这一切都可行。在前端,我想添加一个部分来控制照明。我想通过简单地显示数据库中存储的每种LED颜色的值开始。我为每个要显示以下值的LED字符串创建了一个新的控制器:

'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 }}

这可能是某种异步问题,但我的角度不错的JS较弱。任何帮助都会很棒。

Kildareflare

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

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

 reefController.config.data = data;

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

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

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

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

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

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

更进一步,最佳实践是保存对服务内部服务器返回的数据的引用;原因是服务是单例-因此可以在控制器之间共享此数据服务及其数据。

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

然后在我们的控制器中...

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

更新

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

然后将其注入到控制器中。并添加一个调用新方法以将服务用于数据并分配给模型。然后可以在视图中显示它。

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

然后在视图(HTML)中:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

显示来自数据库Jquery的选定值

来自分类Dev

显示来自sqlite数据库的列值

来自分类Dev

显示来自数据库 Django 的复选框值

来自分类Dev

显示来自数据库PDO的数据

来自分类Dev

显示数据库值

来自分类Dev

显示数据库值?

来自分类Dev

显示来自Firebase数据库的消息

来自分类Dev

显示来自数据库单元的信息

来自分类Dev

显示来自android数据库的图像

来自分类Dev

显示来自数据库的主题标签

来自分类Dev

显示来自数据库的图像

来自分类Dev

显示来自 phpMyadmin 数据库的图像

来自分类Dev

来自数据库的LARAVEL输入值

来自分类Dev

来自数据库的LARAVEL输入值

来自分类Dev

使用mvc显示复选框来自数据库的数据值

来自分类Dev

AngularJS 从数据库插入和显示

来自分类Dev

显示来自多个数据库表的数据

来自分类Dev

以html形式显示来自sqlite数据库的数据(phonegap)

来自分类Dev

PDO显示来自数据库的每个特定ID的数据

来自分类Dev

列表视图未显示来自Android数据库的数据

来自分类Dev

显示来自其他表的mysql数据库数据

来自分类Dev

显示来自 Firebase 实时数据库的数据

来自分类Dev

不显示数据库值

来自分类Dev

使用数据库值显示图像

来自分类Dev

在图像上显示数据库值

来自分类Dev

在日志中显示来自SQLite数据库的ArrayList

来自分类Dev

在模式引导窗口中显示来自数据库的图像

来自分类Dev

显示来自MySQL数据库中路径的图像

来自分类Dev

来自sqlite数据库的ios图像显示