What can be done to prevent function from being treated as instance members within a controller's scope?

When using angularJS 1.3, the following code snippet showcases the functionality:

<!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.20/angular.js"></script>
            <script type="text/javascript">
                var app = angular.module("sample", []);
                app.controller("emp", function(){
                        this.Name = "jag";
                        this.sal = "4500";
                        this.getAnnualSal = function(){
                            return (this.sal) * 12;
                        }
                    });
            </script>
        </head>
        <body ng-app="sample">
            <div ng-controller="emp as o">
                Hello {{o.Name}}, your annual salary is {{o.getAnnualSal()}}

            </div>
        </body>
    </html>

The usage of getAnnualSal as a controller instance member may seem odd. Each instance of the emp controller has its own specific getAnnualSal method.

The scope of the emp controller instance can be visualized like this:

https://i.sstatic.net/D3lWB.png

If it is more logical to maintain getAnnualSal as prototype members, please provide the syntax for doing so.

Answer №1

If you're looking to define your controller as a separate class in AngularJS, one way to do this is by creating a standalone function for it and then using the prototype property to add methods to it.

function MyController() {
    this.Name = "jag";
    this.sal = "4500";
} 
MyController.prototype.getAnnualSal = function(){
    return (this.sal) * 12;
}
var app = angular.module("sample", []);
app.controller("emp", MyController);

If you need to include custom injections like $scope or $rootScope, you can modify your controller function accordingly:

function MyController($scope) { ... all the former code ... }
...
var app = angular.module("sample", []);
app.controller("emp", ['$scope', MyController]);

If you have any questions regarding injections, it's recommended to consult the official tutorial or documentation (e.g. $provide). The key difference lies in whether you use an anonymous function or a named function, with the latter always acting as a constructor function.

Answer №2

Consider using a directive instead of just a controller to address certain scenarios.

  1. How would you handle DOM manipulation within the controller's scope?
  2. What if there is a need for multiple instances of this controller as previously mentioned?
  3. Would incorporating an HTML template be necessary?

One important practice to follow is to assign the controller instance to a variable at the beginning of the scope for future reference.

app.controller("emp", function(){
                        var vm = this;
                        this.Name = "jag";
                        this.sal = "4500";
                        this.getAnnualSal = function(){
                            return (vm.sal) * 12;
                        }
                    });

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

Every attempt to connect with the webservice via an ajax call has ended in failure

I am encountering an issue with a webservice call that I am making using jQuery's AJAX method. Despite receiving JSON data from the webservice when accessed directly through the browser, my site always triggers the error function rather than the succe ...

Restrict the quantity of recommendations provided by the AutoComplete feature

After exploring the autocomplete API from https://material-ui.com/api/autocomplete/, I am unable to figure out a way, given my basic understanding of javascript, to restrict the display of a specific number of options beneath the TextField. I am working o ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Unable to retrieve file from server

Apologies for the basic question, but I'm feeling a bit lost at the moment. I've been diving into learning JavaScript and decided to set up a page on the 00webhost site to experiment and run tests. Everything was going well until I hit a roadblo ...

"Node.js is giving an error stating that the object does not have a

I am attempting to save the user details from the registration form into a JSON file for authentication purposes. However, I am having trouble appending the data in the correct format. Here is the code snippet that I have tried: var filename = "./user_log ...

What is the reason that the slick slider is unable to remove the class filter?

Having troubles with my slickUnfilter function, even though slickFilter is working perfectly? Here's a snippet of my HTML: <div class="slider-wrapper" id="wrapper"> <div class="post" id="post1"&g ...

Update background to full screen and include text when hovering over DIV

Currently, I am utilizing Bootstrap and have a layout with 6 columns containing icons/text within. I desire to implement a hover effect where each column triggers a background change in transition for the entire section. In addition, text and button elemen ...

The property 'scrollHeight' is undefined and cannot be read

I've created a messaging system using javascript and php, but I'm facing an issue. When new messages are received or the chat log grows longer, it creates a scrollbar. The problem is that when a new message arrives, the user has to manually scrol ...

The jQuery button function is not compatible with Google Graph

Upon review below, I have successfully created the getChart() function. It functions properly when called independently, however, it fails to display the chart when enclosed within $(document).ready(function(){...}). The file is also attached for referen ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...

What is the best way to eliminate the content of an element using javascript/typescript?

The progress bar I'm working with looks like this: <progress class="progress is-small" value="20" max="100">20%</progress> My goal is to use javascript to remove value="20", resulting in: <progre ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

A guide to selecting the bookmark with a URL that is on a currently opened page

To gain a clearer understanding of my goal, follow these steps: Open the Chrome Browser and go to a URL, such as https://www.google.com. Once the page loads, locate and click on the bookmark labeled "ABC", which contains the URL ({window.open('/ ...

JavaScript Object DeclarationCreating Objects in JavaScript

In this scenario, I have the following code snippet. Upon calling the constructor, an object is created. When updating the fields, modifications are made as shown below. It's important to note that direct modification of the Comment() function is not ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

What is the technique for combining a string and an HTML element using literal values?

Trying to merge text with a hyperlink: const myText = `${t('privacyTxt')}` + `${<a>{t('privacyLink')}</a>}`; output: If you want to know more about our data processing, check out our[object Object] What else do I need ...

How about sending cookies to different controllers?

We are currently developing a Spring-based application that consists of multiple controllers catering to different modules such as user authentication and analytics jobs. The issue we encountered involves setting cookies in our user controller for authenti ...

Does Koa.js have a nested router similar to Express?

Are there any libraries available that offer Express-style nested routers? For example: var koa = require('koa'); var app = koa(); var Router = require('???'); var restApiRouter = Router(); restApiRouter.get('/', function*() ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

Encountering Challenges when Implementing Next.js with Jest

When attempting to run a test in next.js using jest, an error keeps appearing: The issue may be due to the wrong test environment being used. Refer to https://jestjs.io/docs/configuration#testenvironment-string for more information. Consider utilizing the ...