Ionic timer binding issue: troubleshooting tips

Recently, I developed a stopwatch factory service that primarily focuses on running. Please disregard the reset and other functionalities as they are not yet implemented.

Despite setting up $scope.time to capture timer changes, it doesn't seem to update properly.

I've experimented with various methods, with my latest attempt being quite unconventional but worth trying.

Here is how my view looks:

<ion-view view-title="Clock">
  <ion-content>
    <div ng-controller="controller as ClockCtrl">
      <h1 ng-bind="ClockCtrl.time"></h1>
    </div>
  </ion-content>
</ion-view>

This is my Controller:

.controller('ClockCtrl', function($scope, Stopwatch) {
  var vm = $scope;
  $scope.time = "";
  Stopwatch.init($scope);
})

And here's my service setup:

factory('Stopwatch', function() {
  var Stopwatch = (function() {
                var s;
                var isRunning = 0;
                var time = 0;
        var thatElement;
                function run(element){
                    if(isRunning !== 0){
                        time++;
                        s.mills = time % 10;
                        s.secs = Math.floor(time / 10);
                        s.mins = Math.floor(time / 10 / 60);
                        //Stopwatch.currentTime = ("0"+s.mins).slice(-2)+":"+("0"+s.secs).slice(-2)+":"+("0"+s.mills).slice(-2);
            thatElement.time = ("0"+s.mins).slice(-2)+":"+("0"+s.secs).slice(-2)+":"+("0"+s.mills).slice(-2);
                        setTimeout(run, 100);
                    }
                };

                return {
                    settings: {
                        currTime: "",
                        mills: 0,
                        secs: 0,
                        mins: 0,
                        i: 1,
                        times: ["00:00:00"],
                    },
                    currentTime: "",
                    init: function(element) {
                        thatElement = element;
                        s = this.settings;
                        this.start(element);
                    },
                    clear: function() {
                        s.i = 1,
                        s.mins = s.secs = s.mills = 0;
                        s.times = ["00:00:00"],
                        s.results.innerHTML = s.clearButton;
                    },
                    start:function(element){
                        isRunning = 1;
                        run(element);
                    },
                    stop: function(){
                        isRunning = 0;
                    }
                }

            })();
  return Stopwatch;
})

Admittedly, I acknowledge the flaws in my recent approach. Any suggestions or tips would be greatly appreciated since this marks my initial encounter with Ionic and second trial with Angular.

Thank you in advance for your valuable insights!

Answer №1

If you are implementing the controllerAs syntax, remember to assign properties to the controller instance, rather than the $scope object:

.controller('ClockCtrl', function($scope, Stopwatch) {
  this.time = "";
  Stopwatch.initialize(this);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The function is not defined, even though it is located within the same file

I've encountered an issue with my web page where I'm trying to read data from an HTML data table and update it on a PHP file using AJAX queries in JavaScript. Everything was working fine until recently, even though I didn't make any signific ...

What is the process of utilizing a controller to display or conceal a login link?

I have developed a phone directory application that includes a login system. Once the user successfully logs in, the login button is supposed to hide. However, I feel like my approach might not be correct. //html code snippet <ul class="nav navbar-n ...

Turning off devtools in Next.js

Currently, my focus is on developing an application using Next.js and I am in search of a way to prevent the opening of devtools. While exploring npm packages, I came across a promising tool called Disable-devtool - npm link. However, Next.js keeps present ...

JavaScript for Verifying Phone Numbers

After extensive research and tutorials, I am still unable to figure out what is going wrong with my work. I have a button that looks like this: Despite Stack Overflow causing some trouble for me, please ignore the missing class as it is there. This is no ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Display/Modify HTML form

Looking for advice on how to create an interactive HTML form that displays data and allows users to edit it by clicking 'Edit' before submitting changes. Any suggestions on how to implement this functionality? ...

Exploring Passportjs Callbacks and parsing arguments

I'm struggling to grasp the concept behind the custom callback in Passport.js. I'm not sure why it requires (req, res, next) at the end. Shouldn't these values be obtained from closure? app.get('/login', function(req, res, next) { ...

Only one active class is allowed in the Bootstrap Accordion at any given time

I have implemented Bootstrap's accordion on my webpage, consisting of two different sections with unique content. Upon loading the page, the active class defaults to the first element of the first section. However, if I navigate to the "Second" sectio ...

Switch the orientation of a live table moving horizontally to vertically and vice versa

config.previewData = [ { Products:27989, Total Customers:294, Metrics:"MVC", Toner Products:5928, INK Products:22061 }, { Products:56511, Total Customers:376, Metrics:"SMB", ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...

What could be causing the issue with retrieving HTTP requests in Nest.js even after configuring the controller?

After the individual who departed from the company utilized Nest.js to create this server-side system. They established the auth.controller, auth.service, auth.module, auth-token, jwt.strategy, and jwt-payload, with everything properly configured. I verifi ...

Tips for saving the JSON data from a directive so it can be accessed on a different HTML page using Angular

One of my requirements is to retrieve data from an Excel file located anywhere and display it on a separate HTML page. Initially, I managed to display data from multiple sheets on the same page. Now, however, I need to select the file on the first page and ...

What is the best way to merge all project modules into a single file using the r.js optimizer?

While working with the r.js optimizer, I noticed that the final index.html file doesn't seem to allow for referencing just a single script without making any async calls to other scripts during a user's session. It appears to generate multiple gr ...

AngularJS - Show Banner after two rows, then show two more rows

I'm attempting to showcase a Banner <div> after 2 rows of 4 x "col-md-3", succeeded by another 2 Rows - thus, resulting in the following markup: <div class="col-md-3">1</div> <div class="col-md-3">2</div> <div clas ...

Conserving node.js native imports for Electron with rollup

I am working on a project using Electron, Svelte, and Typescript. Initially, I used a specific template from here, but it restricted access to node.js built-in imports like fs for security reasons in the browser/electron frontend. However, I do not requir ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

Tips for managing and identifying canceled requests in an Angular HTTP interceptor

Having trouble handling cancelled requests in my http interceptor. Despite trying various methods from SO, I can't seem to catch it. Here is an example of how my interceptor looks: public intercept(req: HttpRequest<any>, next: HttpHandler) { ...

Having trouble with the JQuery class selector?

Having a bit of trouble trying to select an element based on its class using $(".class"), and I can't seem to figure out why it's not working. So, the deal is - I have this image element that should appear when a function gets triggered: $("#co ...

"Optimizing npm packages for front-end web development in vanilla JavaScript: A guide to bundling for production deployments on

My website is built using vanilla HTML/CSS/JavaScript with ES6 modules and can be deployed to GitHub pages and Netlify. I have set up my site by importing "main.js" in my HTML like this: <script src="js/main.js" type="module" defer&g ...