Jason Jason - 4 months ago 19
Javascript Question

How to access a value from a Phonegap plugin in an Angular controller?

I'm new to Angular and getting stuck on something I hope is simple. I need to read the app version using this plugin (app version plugin). I know I need to read the version in the run handler but I can't figure out how to get it into my controller so I can data-bind to it.

Here's my code so far which reads the version properly:

var appVersion = "0.0.0";

var example = angular.module('surj', ['ionic'])
.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
cordova.getAppVersion.getVersionNumber(function (version) {
appVersion = version;
});
});
})

.controller('TestCtrl', function() {
var controller = this;

//this.version = appVersion;
this.getVersion = function() {
return appVersion;
}
})


I'm sure I'm just missing something obvious. Any thoughts?

Thanks,
Jason

Answer

Okay, after trying many different methods, here's what I came up with.

var example = angular.module('App', ['ionic'])
    .controller('AppCtrl', ['$scope', '$ionicPlatform', function($scope, $ionicPlatform) {
        var controller = this;

        // Properties
        controller.appVersion = "NA";

        // Methods
        controller.setVersion = function (version) {
            $scope.$apply(function() { controller.appVersion = version });  // Update the value and trigger the data-binding to refresh
        }

        // Init
        $ionicPlatform.ready(function () {
            cordova.getAppVersion.getVersionNumber(function (version) {
                controller.setVersion(version);
            });
        });
    }])

It's actually quite simple, you just use $scope.$apply to update the databinding once the version gets updated.