Search code examples
javascriptangularjshtmlibeaconmonaca

how to run a angular js controller continuously(in every 5 seconds) after called the first time


here is my angular js file(app.js)when I call the controller(uuidCtrl) it will trigger the uuidCtrl Controller.when I want to call the controller 2 times i have to load the page 2 times.But I want to run it continuously after called the first time.Hope You have some solution for this.

var app = angular.module('myApp', ['onsen']);

app.service('iBeaconService', function () {
    this.currentBeaconUuid = null;
    this.onDetectCallback = function () {
    };

    this.beacons = {
        "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx": {
            icon: 'img/1.jpg',
            rssi: -200,
            proximity: PROX_UNKNOWN,
            name: 'Beacon',
            number: '1',
            id: '000265C9'
        }

    };

    createBeacons = function () {
        //some code
    };

    this.watchBeacons = function (callback) {
        ///some code
    };

});
app.controller('uuidCtrl', ['$scope', 'iBeaconService', function ($scope, iBeaconService) {

    $scope.beacons = iBeaconService.beacons;

    var callback = function (deviceData, uuid) {

        iBeaconService.watchBeacons(callback);
    }
}]);

This js should be looped in the application to scan beacons nearby

This is where i call the controller

<ons-page id="page2" ng-app="myApp" ng-controller="uuidCtrl">

Solution

  • You can use $interval

    app.controller('uuidCtrl', ['$scope', '$interval', 'iBeaconService', function ($scope, $interval, iBeaconService) {
      ...
      $interval(function() {
        // do whatever you want to execute every 5 sec
      }, 5000) // 5000 ms execution
      ...
    

    Also, you probably want to call the watchBeacons, and pass a callback, not like you do now that you simply define a function

    $scope.beacons = iBeaconService.beacons;
    
    iBeaconService.watchBeacons(function (deviceData, uuid) {
      // do whatever
    });
    

    Hope this helps.