As a newcomer to Angular, I am facing some initial challenges. I have created a small app with phonegap, onsen ui, and angularjs that utilizes the nfc-plugin. My goal is simple - to read a tag-id from an nfc-tag. Everything works perfectly when I include all my code within the controller.
Here is what it looks like:
app.controller('Page3Ctrl', function($scope, Data) {
$scope.item = Data.selectedItem.title;
$scope.save = function() {
Data.selectedItem.title = $scope.item;
$scope.ons.navigator.popPage();
};
// Get the ID Number from the tag
$scope.onNfc = function(nfcEvent) {
var tag = nfcEvent.tag;
var taglesen = nfc.bytesToHexString(tag.id);
$scope.$apply(function() {
$scope.item = taglesen;
});
};
nfc.addTagDiscoveredListener(
$scope.onNfc, // tag successfully scanned --> call $scope.onNfc
function (status) { // listener successfully initialized
$scope.nfcok = "NFC Reader ist ready";
},
function (error) { // listener fails to initialize
$scope.nfcok = "NFC Reader ist nicht ready";
}
);
});
<ons-page class="center">
<div ng-controller="Page3Ctrl">
<ons-text-input ng-model="item" style="margin:10px;"></ons-text-input><br>
<ons-text-input ng-model="nfcok" style="margin:10px;"></ons-text-input><br>
<ons-button ng-click="save()">Save</ons-button>
<ons-button ng-click="onNfc()">Scan NFC</ons-button>
</div>
</ons-page>
Now, I want to move the NFC-reading functionality to a separate file called services.js and incorporate it into a factory. However, I am facing challenges in doing so.
I attempted the following approach, but unfortunately, it did not work. I may need some guidance or perhaps I am approaching this in the wrong way:
myApp.factory('onNfc', function() {
this.getNfc = function(nfcEvent) {
var tag = nfcEvent.tag;
var taglesen = nfc.bytesToHexString(tag.id);
return taglesen;
}
nfc.addTagDiscoveredListener(
this.getNfc(), // tag successfully scanned
function (status) { // listener successfully initialized
$scope.nfcok = "NFC Reader ist ready";
},
function (error) { // listener fails to initialize
$scope.nfcok = "NFC Reader ist nicht ready";
}
);
});
app.controller('Page3Ctrl', function($scope, Data, onNfc) {
$scope.item = Data.selectedItem.title;
$scope.save = function() {
Data.selectedItem.title = $scope.item;
$scope.ons.navigator.popPage();
};
$scope.$apply(function() {
$scope.item = onNfc.getNfc();
});
});
I appreciate any assistance provided.
Warm regards,