Updating a Vanilla JS variable within the scope of an Angular JS controller: A step-by-step guide

let num = 1;

function increaseCounter() {
    num++;
}  

angular.module('myapp')  
    .controller('MainCtrl', function($scope) {  
        $scope.b = num;  
    });

I am trying to continuously track the variable num within the scope of $scope.b

<button onclick="increaseCounter()">Click me</button>

Is there a way to keep monitoring it? I attempted to set a watch on num, but couldn't get it to function properly.

Answer №1

Utilize the ng-click directive

<button ng-click="incrementCounter()">Click me</button>

Define an incrementCounter function in the $scope and then invoke a global method to update b within the ngClick handler.

angular.module('myapp')
    .controller('MainCtrl', function ($scope) {
        $scope.b = a;
        $scope.incrementCounter = function(){
             incrementCounter();
             $scope.b = a;
        };
    });

Avoid defining functions in Global Scope. It is recommended to use Angular's service or factory instead.

var app = angular.module('myapp');
app.controller('MainCtrl', ['$scope', 'myFactory', function ($scope, myFactory) {
    $scope.b = myFactory.getData();
    $scope.incrementCounter = function () {
        myFactory.incrementCounter();
        $scope.b = myFactory.getData();
    };
}]);

app.factory('myFactory', function ($http) {
    var a = 0;
    return {
        incrementCounter: function () {
            return a++;
        },
        getData: function () {
            return a;
        }
    };
});

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

Check access tokens from various front-end applications (Client ID) with the help of okta-jwt-verifier

Is there a way to verify access tokens generated from multiple front end Angular apps using the same backend API by sending in an array of clientIds? const OktaJwtVerifier = require("@okta/jwt-verifier"); const oktaJwtVerifier = new OktaJwtVerifi ...

Tips for including a verification symbol next to your username

How can I implement a verification badge next to a user's username on a website using jQuery, JavaScript, PHP, HTML, and CSS? Currently, I am using isset($user[verification]) to display the badge, but I believe this approach is not optimal as it requi ...

A guide on sending an array to an Express API

I have been working on creating APIs using Express.js and SQL Server. Posting an object was easy and simple, but now I have a new challenge: how do I post an array? Imagine I have a table that only stores two parameters: Table_A Id | CouponId In this ta ...

What is the best way to sort an array of objects based on their properties?

I am working with an array of objects: let response = [{"id": 1, "name": "Alise", "price": 400, "category": 4}]; In addition to the array of objects, I have some arrays that will be used for filtering: let names = ["Jessy", "Megan"]; let prices = [300, ...

angular-bootstrap-mdindex.ts is not included in the compilation result

Upon deciding to incorporate Angular-Bootstrap into my project, I embarked on a quest to find a tutorial that would guide me through the download, installation, and setup process on my trusty Visual Studio Code. After some searching, I stumbled upon this h ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Repeated failures in the CodeIgniter JavaScript function

Currently I am developing a donation store using CodeIgniter. I have been focusing on implementing the cart functionality, and have created a small card to display the store items. The card allows users to add items to their cart using an AJAX request to p ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

What could be causing json_decode to return NULL in this scenario?

I have a custom array that I've created with the following structure: [{ "assetPreviewUrl":"pic1.jpg", "assetUrl":"pic2.jpg" }, { "assetPreviewUrl":"pic3.jpg", "assetUrl":"pic4.jpg" }] My approach involves stringifying this array and ...

What is the top choice instead of using the jQuery toggle() method?

After jQuery deprecated the toggle() method, I began searching for alternative ways to toggle classes on Stack Overflow. I came across various other methods to accomplish the same task (Alternative to jQuery's .toggle() method that supports eventData? ...

Error: JSON data abruptly terminated (Node.js)

As a beginner developer diving into the world of API's, I've encountered a recurring error in Node.js that seems to be causing crashes: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymo ...

Generating a fresh PHP webpage through the administration dashboard

Currently, I am working on developing a blog page using PHP. One key aspect that I am struggling with is figuring out how to efficiently create new posts from the admin panel. Any suggestions or advice would be greatly appreciated! ...

Error message "Sphere undefined" encountered in ThreeJS Water2 example

I've been experimenting with setting up the basic ThreeJS Water2 example that can be found here: You can access the source code here: https://github.com/mrdoob/three.js/blob/master/examples/webgl_water.html The process appears simple at first glance ...

Utilizing AngularJS to render nested array objects within HTML attributes

I have some data that looks like this: Continent":"Africa", "Countries":{ "Nigeria":[ { "Id":"2", "ColumnName":"Lagos", "Type":"Textbox", } ] } I am wondering if it i ...

Sending information from tinyMCE text field to PHP using AJAXgetMethod

When I use a TinyMCE 4.0 text field to post HTML data through AJAX, I am encountering an issue where the data doesn't reach the server side properly. In Firefox Firebug, it shows that I have posted this data: attendanceID=&noteID=&Category=2 ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Understanding the significance of an exclamation point preceding a period

Recently, I came across this code snippet: fixture.componentInstance.dataSource!.data = []; I am intrigued by the syntax dataSource!.data and would like to understand its significance. While familiar with using a question mark (?) before a dot (.) as in ...

Display a loading bar while uploading files in an Angular directive

How can I implement a progress bar in an Angular directive for file uploads? app.directive('uploadPanel', function () { return { restrict: 'E', scope: { action: '@' }, }) ...

Utilizing VueJS, Webpack, and the Power of Video

I'm running into an issue when attempting to use vue-cli with the webpack-simple template. Upon importing my video file: <video src="./assets/twp-logo-video.mp4" id="initial-logo" type="video/mp4"><!-- 700 x 700 --> </video> I en ...

Extracting a specific range of values from a JSON object

Can anyone help me with filtering a range of values from a json object? Here is the range data I am working with: const contractAmountRange = [ { id: '1', min: 0, max: 100000, description: 'Less than $100,000' }, { id: ...