The inefficiency of printing repeatedly when a function is invoked in AngularJS

When I call a function from the controller scope, why are the values printed three times in the console?

SOURCE

<!DOCTYPE html>
<html ng-app="myModule" >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
</head>
<body ng-init="priceList='promo03,promo04'">
<div ng-controller="PricingController" >
    {{splitArray()}}
</div>
<script>
var myModule = angular.module('myModule',[]);

myModule.controller('PricingController',['$scope', function($scope){
    $scope.priceString = $scope.priceList;
    $scope.array = [];
    $scope.splitArray= function(){
        console.log($scope.priceString);
        $scope.array = $scope.priceString.split(",");
        console.log($scope.array[0]);
        console.log($scope.array[1]);
    };
}]);
</script>
</body>
</html>

CONSOLE OUTPUT

promo03,promo04 
promo03
promo04 
promo03,promo04 
promo03 
promo04 
promo03,promo04 
promo03
promo04 

Expected Output

promo03,promo04 
promo03
promo04 

Answer №1

Every time the Angular digest loop runs, this function gets called. If you leave your program running, more logs will pile up.

To prevent this, make sure to call your function within your controller instead of binding it directly in your HTML.

For example:

$scope.breakApart = function(){
        console.log($scope.stringToBreak);
        $scope.array = $scope.stringToBreak.split(",");
        console.log($scope.array[0]);
        console.log($scope.array[1]);
    };
$scope.breakApart();

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

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

Is there a way to retrieve SQL information through an API and then incorporate that data into react-native-svg charts? I have an API that contains data I would like to retrieve and showcase

I am utilizing an API to retrieve data, which includes the execution of SQL queries. The API is responsible for fetching data and running these queries. I am looking for a way to replace the static data in my charts with dynamic data fetched from the API. ...

Add data to a size guide

My coding project involved creating a sizing chart using HTML, CSS, and JavaScript. The chart allows users to select their preferred units of measurement (metric or imperial). I used JavaScript to dynamically update the values in the chart based on the sel ...

Utilize React Helmet for Dynamic Page Titles

Currently, I am utilizing Gatsby with react-helmet to manage the title and meta tags in the head of my website. However, I am eager to find a way to also display this title in the actual text of the page through a global <Header /> component. In proj ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

The JavaScript code malfunctions when I introduce a new HTML tag

I am attempting to create a simple photo gallery using PhotoSwipe. However, I have encountered an issue where certain functions like Previous and Next buttons stop working when I add new HTML elements. Here is the original code: <div class="my-gallery ...

React TextField is not accommodating the new line character ' ' causing recognition issues

Explanation I have encountered an issue while using Material UI TextField and mapping through an array of objects fetched from a MongoDB database. Here is the code snippet in question: {state.map((item) => ( <TextField name=" ...

Preventing cross-site scripting attacks with the help of dynamic pre elements

An expert recommended that the user content, replyContent, be surrounded by a <pre> tag to prevent XSS attacks. However, why is it commonly believed that this code effectively prevents XSS? I attempted to inject </pre><script>alert("XSS" ...

The UI Bootstrap Datepicker requires a second click in order to update the month

I am currently using the UI Bootstrap Datepicker component. An issue arises when I try to select the next month - the datepicker itself updates correctly, but the displayed month name does not change (refer to picture 1 and 2). Interestingly, after select ...

Synchronize variables in a single Vue.js file

In my Vue file (version 2.x), I have three fields - input1 x input2 = result. Whenever one of these fields is changed, the other two should update simultaneously. I attempted to use the watch property but it resulted in an infinite loop as the watchers ke ...

Creating Dynamic UI in React Native by Displaying POST Request Data on Screen

Here's a scenario where I have set up a post route: router.post("/projects", async (req, res) => { const { projectName, projectDescription, projectBudget, projectDuration, industry, companyName, numberOfEmployees, ...

``I am facing an issue where Angular fails to update a $scope variable after

I am experiencing an issue with my AngularJS script. I have created a website for my personal network where I can control bulbs. I access the site on both my computer and mobile device. When I turn on a bulb on my mobile phone, the light goes off. I can ...

Encountering an Uncaught Error in Angular 1.2.9 despite the inclusion of ngRoute module

Even after ensuring the ngRoute file is included and ngRoute is added to dependencyInjection, I am still encountering the following error: Error: [$injector:modulerr] http://errors.angularjs.org/1.2.7/$injector/modulerr?p0=demoModule&p1=Error….org% ...

Leveraging Angular 2's HTTP client functionality with ES5 syntax

We are in the process of upgrading our Angular 1 application to Angular 2, module by module. Since our current project is built on es5, we have decided to stick with it while transitioning to Angular 2. We have a good understanding of upgradeAdapter and DI ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

JSON will soon be receiving an Angular directive

Having a directive: This data object is passed: <a-link options = "data"></a-link> Here's the code for my directive: .directive('aLink', function() { return { restrict: 'AE', replace: true, template: ...

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

When a HTML table is generated from imported XML, DataTables will be applied

I am facing a challenge with my code and would appreciate some help. I am trying to load an XML file using jQuery and then use DataTables on my HTML table. However, the plugin doesn't seem to be functioning correctly. When I manually create an HTML ta ...

What are the keys that have the specified string in them?

Provided information includes : var people = [ { 'myKey': 'John Kenedy', 'status': 1 }, { 'myKey': 'Steeven Red', 'status': 0 }, { 'myKey': 'Mary_Kenedy', 's ...