The AngularJS Controller Function

I'm working with a code snippet that includes an Angular Modular Controller containing a function inside the controller itself with a call. I'm unsure if this coding practice is allowed in JavaScript or Angular, and if it is, how does it work? Take a look at the code format below:

obj.controller('CartController',function($scope){

  $scope.totalCart = function(){
    var total = 10;     
    return total;
  }
  function calculate(){
    ...Some Logic..
  }

  $scope.$watch($scope.totalCart, calculate);
)};

I'd appreciate some clarification on whether this type of function definition and call within a controller is permitted in Angular/Javascript.

Answer №1

Utilizing the calculate() function as a private method within the confines of the CartController is recommended if the function does not need to be accessed from the view. By marking it as a private function, it signals that its usage should be limited within the controller itself and caution should be exercised when considering its use in the view. Furthermore, accessing objects within the scope of the CartController is possible from within the calculate function, including objects passed as parameters to the controller.

A proper JavaScript function declaration allows for easy referencing by name. A common practice is declaring functions beforehand and then assigning them to properties of an object (such as $scope):

function someFn(...) { ... }

function someOtherFn(...) { ... }

...

$scope.someFn = someFn

In this example, clarity is prioritized by making someFn accessible while keeping someOtherFn private.

It's worth noting that defining functions like function nameFn(...){...} is referred to as a function statement, whereas a similar approach can be taken with var nameFn = function(...) {...} (known as a function expression). The key distinction lies in the fact that:

 someFn();
 var someFn = function(...) {...}

is invalid, while:

 someFn();
 function someFn(...) {...}

is acceptable.

Situations may arise where using the latter pattern becomes necessary, as illustrated in my response to a query about Angular injector decoration here.

Answer №2

function startLaunch(which) {

};
var _func = function () {...}

Answer №3

Acceptable definition, yielding a similar outcome to:

$scope.$watch($scope.totalCart, function(){..implementing some sort of logic...})

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

Clicking buttons in AngularJS

I've developed a button that, when clicked, triggers an AJAX call and binds the server response obtained through AJAX to a table using AngularJS. The issue I'm facing is that the data should appear on the webpage on the first click of the button, ...

Revamp webpage content and links without refreshing the page, similar to the navigation menu on Facebook

My website consists of two HTML pages, specifically contact.html and index.html. Additionally, there is a menu-sidebar and a content div integrated into the web design. There are two main objectives I am looking to achieve: 1. The ability to swap between ...

Execute the function that has been passed through a data attribute

I am attempting to execute a function using its name, which is passed through a data attribute in the HTML. I have made an attempt with the code below: HTML: <div class="generic-select" data-help-on-shown="genericFunction" > </div> ...

Transform JavaScript into Native Code using V8 Compiler

Can the amazing capabilities of Google's V8 Engine truly transform JavaScript into Native Code, store it as a binary file, and run it seamlessly within my software environment, across all machines? ...

Submitting several individual files through distinct Dropzones within a single form

I have implemented a form that allows users to add multiple rows, each containing name and avatar fields. My goal is to utilize Dropzone.js in order to create individual droppable areas for each avatar field. Every time a new row is added, a new Dropzone ...

Tips for correctly mapping a shuffled array in React/Next without triggering a hydration mismatch error

I've been working on a Next.js website and I'm trying to display a randomized list of famous quotes. To achieve this, I'm using lodash to shuffle the array of quotes and then mapping them onto the page. import { useMemo } from 'react&ap ...

Is there a way for me to retrieve data from a v-for loop in VueJS with the Quasar Framework?

I am currently working on a q-markup-table code to display products based on a search query. I have successfully implemented a button that allows the user to select a row from the table, and once selected, the row data is sent to an array named "selected ...

AngularJS: Potential uncaught rejection encountered with the $http.get() method - Error Status: -1 due to CORS

Encountering an error while using a HTTP GET method: :63502/Scripts/angular.js:14525 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","para ...

Determining the data type of a textbox value in JavaScript: String or Number?

I am encountering an issue with the code below: <input type="text" value="123" id="txtbox"> <script> var myVar = document.getElementById('txtbox').value; if (myVar.substring) { alert('string'); } else{ alert('number&a ...

Ways to identify when the user has stored a file on their local disk using Angular/NodeJS

In my NodeJS backend, I am generating a JSON file temporarily to store the information provided by the user in a form. Upon clicking the download button at the end of the form, I execute a Python script within NodeJS to verify the data and create a tempora ...

Using JavaScript to place a particular tag at a designated position

I have a string that looks like this: var txtstr='<p>Text 1</p><p>&nbsp;</p><p>Text &nbsp;2</p><p>&nbsp;</p><p>Text 3&nbsp;</p>'; I have an <img src=..../> tag and ...

Launch the database-connected gallery in a lightbox interface

Having a small issue here - attempting to create an anchor tag labeled "Photos" that, when clicked by the user, triggers Ajax to retrieve results from a PHP/MySQL database and display images within a lightbox. This is what I have attempted so far: <a ...

Choosing the Laravel 6 option for editing via AJAX: A step-by-step guide

I am looking to update a user who resides in a specific state within a country. The country and state fields are dropdown select options, with a relationship established between them and the user. The state field is populated based on the selected country. ...

Using Javascript to parse a json file that contains additional content at the beginning

I am attempting to access a JSON URL, but the JSON is displaying some extra characters before it starts. The structure of the JSON script is as follows: throw 'allowIllegalResourceCall is false.'; { "name":"mkyong", "age":30, "addres ...

Is it possible to swap images by clicking on them?

Let's say I'm working with 3 images. Image A, B and C. A is the main image initially. If I click on image B, it will become the main image and image A will take its place in the old position. The same condition applies when B is the main image a ...

NodeJs for Updating Data: An Essential Guide

When attempting to update user data in my database using a Node.js app with ExpressJS, I encountered the following error in the terminal: sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version fo ...

How can one effectively separate logic in AngularJS for optimal performance?

I've been diving into AngularJS and it's been quite fascinating, although I do run into some architectural challenges at times. Let me illustrate with an example. Imagine we have an application that enables users to create bills. Each bill consi ...

Using `appendChild` in combination with `createElement`

Is there a difference between these two approaches: var div = document.createElement('div');//output -> [object HTMLDivElement] document.getElementById('container').appendChild(div); and: var div = '<div></div>&a ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...

What is the best way to handle the select event for a jQuery UI autocomplete when there are images involved?

Looking for help with creating an autocomplete feature with images on this jsfiddle. Despite trying to capture the event when a user selects an image, it doesn't seem to work properly: $("#input").autocomplete({ //source: tags, so ...