我有API的Methode。它返回一个解析为$ ctrl(?)对象的promise。此对象应包含度量,并在收到新数据时进行更新。
getMeasurements.latest(filter) //only a object to filter through all measurements
.then(function (latestMeasurement) {
$ctrl.latestMeasurement = latestMeasurement;
});
我的问题是我不知道如何处理这些数据或将其显示在我的html文件中。 $ ctrl如何工作?
此处为API的documentation
答案 0 :(得分:8)
$ ctrl 是控制器中的视图模型对象。这个$ ctrl是你选择的名字( vm 是另一个最常见的名字),如果你检查你的代码,你可以看到定义为 $ctrl = this;
,所以基本上它是控制器功能的 this
关键字。
现在,如果您使用$ctrl.latestMeasurement = 'someValue'
,那么就像您正在向控制器函数添加属性latestMeasurement
。
现在如何在HTML中使用它?
要以HTML格式访问latestMeasurement属性,您的代码必须具有<h1>{{$ctrl.latestMeasurement}}</h1>
(H1标记只是一个示例。)
此处 $ ctrl 与我在控制器部分上所解释的不同。这里$ ctrl是用于控制器的 controllerAs
属性的值。但$ctrl
是controllerAs
属性的默认值,因此您的代码可能没有定义controllerAs属性,因此Angular将在HTML中采用默认值$ctrl
。
这是大多数人感到困惑的地方。所以让我解释一下,
假设您的新控制器已将this
关键字声明为变量vm
,并将controllerAs
属性设置为myCtrl
,即
controllerAs: 'myCtrl'
在定义控制器属性时。
var vm = this;
。
在js中的这种情况下,您必须使用vm
来设置值,而在HTML中,您必须使用myCtrl
。例如,
在JS控制器函数vm.test = 'Hello world';
<span ng-bind="myCtrl.test"></span>
结果 Hello world 将显示在您的页面中。
为什么$ ctrl而不是$ scope?
视图模型对象模型概念在AngularJS 1.5中引入,它实际上是迁移到Angular 2的一部分,其中$ scope不再存在。所以在1.5中他们引入了新的approch但没有完全删除$ scope。
希望答案有所帮助。
对于基本的Javascript概念,您可以看到http://javascriptissexy.com/16-javascript-concepts-you-must-know-well/
有关更详细的AngularJS $ ctrl概念,您可以看到https://johnpapa.net/angularjss-controller-as-and-the-vm-variable/
答案 1 :(得分:1)
我想你正在寻找this。
在这种情况下,
$ctrl.latestMeasurement
可以表示:
$ ctrl ,即运行此代码的控制器。例如,您可以通过$ scope更改它,并获得相同的结果。
latestMeasurement ,您要存储测量的最后一个值的变量。
要解释我的观点,请看下面的代码
<div ng-app="MeasurementApp">
<div ng-controller="MeasurementController">
<h1>{{latestMeasurement2}}</h1>
</div>
</div>
在那里你可以看到一个简单的angularjs应用程序,它在div中显示一个名为latestMeasurement2的变量,其控制器名为MeasurementController。然后,要显示该值,请检查您的代码。
angular.module('MeasurementApp', [])
// creating the controller
.controller('MeasurementController', function(c8yMeasurements, $scope) {
// creating the variable and let it empty by now.
$scope.latestMeasurement2 = "";
// Your code
var filter = {
device: 10300,
fragment: 'c8y_Temperature',
series: 'T'
};
var realtime = true;
c8yMeasurements.latest(filter, realtime)
.then(function (latestMeasurement) {
// The latestMeasurement is where the measurement comes
// Here we just assign it into our $scope.latestMeasurement2
$scope.latestMeasurement2 = latestMeasurement;
});
});
正如文件所说
// $scope.latestMeasurement2 will be updated as soon as a new measurement is received.
$scope.latestMeasurement2 = latestMeasurement;
希望这有帮助!