我已经创建了一个切换列表来选择蓝牙设备并连接它,我为他们创建了一个controller.js和service.js。但是,ng-change
仅在首次加载离子切换时触发,并且之后不会触发更改。
以下是我的setting.html
:
<ion-toggle ng-repeat="item in devicesList"
ng-model="item.checked"
ng-change="connectDevice(devicesList)">
{{ item.address }}
</ion-toggle>
这是我的settingController.js
:
(function () {
'use strict';
angular.module('i18n.setting').controller('SettingController', SettingController);
SettingController.$inject = ['$scope','SettingService'];
function SettingController($scope, SettingService) {
$scope.devicesList = [];
$scope.scanDevices = SettingService.scanDevices($scope.devicesList);
$scope.connectDevice = SettingService.connectDevice($scope.devicesList);
};
})();
这是我的settingService.js
:
(function(){
'use strict';
angular.module('i18n.setting').service('SettingService', SettingService);
SettingService.$inject = [];
function SettingService(){
var self = this;
this.scanDevices = function(devicesCollection) {
window.bluetoothSerial.discoverUnpaired(function(devices) {
console.log("in discoverUnpaired callback, setting page");
devices.forEach(function(device) {
console.log(device.name);
device.checked = false;
devicesCollection.push(device);
});
}, function(error) {
console.log("in discoverUnpaired error function");
console.log(error);
});
};
this.connectDevice = function(devicesCollection) {
console.log(devicesCollection);
console.log("In connectDevice");
for (var i =0; i<devicesCollection.length; i++)
{
console.log(devicesCollection[i].id + " " + devicesCollection[i].checked);
if (devicesCollection[i].checked == true)
{
console.log(devicesCollection[i].name);
window.bluetoothSerial.connect(devicesCollection[i].address,
function(data) {console.log("This device is"+macaddress); console.log(data);},
function(error) {console.log(error);});
}
}
};
}
})();
如果我直接在settingController.js
中定义此功能,它可以正常工作并且可以检测到切换的每次更改。此外,我注意到即使我没有点击按钮,我的scanDevices
功能也会被触发。我不知道为什么会这样。会不会有人告诉我是什么原因造成的?任何帮助,谢谢
答案 0 :(得分:1)
控制器应将服务功能放在范围内;不是对服务功能的调用。
scanDevices
由于return
函数没有scanDevices($scope.deviceList)
语句,undefined
会返回$scope.scanDevices
。因此undefined
设置为<button class="button button-stable"
ng-click="scanDevices(devicesList)">Scan Devices
</button>
。
你能解释为什么在我按下扫描按钮之前调用scanDevices?
哪个绑定到:
//ERRONEOUS $scope.scanDevices = SettingService.scanDevices($scope.devicesList); //CORRECT $scope.scanDevices = SettingService.scanDevices;
通过将函数的调用绑定到范围变量而不是函数本身:
SettingService.scanDevices($scope.devicesList)
表达式undefined
在单击按钮之前调用函数。并将$scope.scanDevices
分配给{{1}}变量。