我是Angular的新手。我有一个朋友和我正在做的项目,作为一个" Reef Tank Controller"。它是一个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">
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就此而言很弱。任何帮助都会很棒。
答案 0 :(得分:2)
我在这里可以看到的主要问题是你使用$ 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>