Is it possible for a scope object to access its own properties using the keyword "this"?

Can anyone help me figure out how to calculate the total fees in this example?

$scope.fees = {
    basic: 1,
    premium: 2,
    total: this.basic + this.premium
}

I'm getting an error that says this is undefined. Is there a better way to do this without repeating

$scope.fees.basic + $scope.fees.premium
for total?

If there's a more concise method, please let me know.

UPDATE: I realized I need to define the total property outside of $scope.fees. Like this: $scope.fees.total = ...

Answer №1

If you need to calculate the total fees, you can utilize the following function:

Hello {{ total() }}
function FeeController($scope) {

    $scope.fees = {
    basic: 1,
    premium: 2,

};

  $scope.total = function() {
    return $scope.fees.basic + $scope.fees.premium;
  };

}

Answer №2

The issue with this.basic

When using this, it is being evaluated within the context of the function containing the statement. This means that this does not refer to the $scope.fees object, but rather to the controller itself.

Why
total : $scope.fees.basic + $scope.fees.premium
doesn't work

When trying to evaluate the expression

$scope.fees.basic + $scope.fees.premium
, the $scope.fees object may not exist yet since it is still in the process of being created. Therefore, this can lead to an error message like "Cannot read property basic of undefined".

Solution to the problem

Unfortunately, there may not be a better solution other than what you have already discovered to achieve the desired behavior. It seems like you will need to stick with the current approach for now.

Answer №3

If you're looking to reduce your dependency on $scope, you might want to explore the "controller as class" pattern. Here's an example of how you can implement it:

app.controller('FeeCtrl', function () {
  this.basic = 1;
  this.premium = 2;
  this.total = this.basic + this.premium;
});

You can then directly use this controller in your HTML:

<div ng-controller="FeeCtrl as fee">   
 {{ fee.total }} 
</div>

For more detailed instructions, you can visit this link.

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 data contained in the Response is an extensive script instead of the intended JSON object

Currently, I am in the process of developing a web application using Laravel and Vue.js. In order to retrieve a list of users, I have implemented an axios GET request. However, the response I am receiving is in the form of a Promise object, which I have le ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...

The architecture of Angular controllers

Being a novice in AngularJs, I have a query regarding the controller structure. This particular file is my employeeController.js (function() { angular.module('employeeApp').controller('employeeController', employeeCont ...

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...

Prevent Page Refresh with F5 in Silverlight

Many of the users on my platform are accidentally hitting the F5 key while typing, causing them to lose all their work. I don't want to completely block the ability to refresh the page. I attempted using the following JavaScript solution, however it ...

The Ocelot API Gateway is a powerful tool for managing

I encountered an issue while working on my API gateway project. I initially installed the latest version of Ocelot (16.0.1), but it did not function correctly. The problem was resolved by reverting back to Ocelot version 15.0.6, while keeping my .NET Core ...

The object you are attempting to use does not have the capability to support the property or method called 'after'

When attempting to add a div tag dynamically using javaScript, I encountered an issue with the .after function not working in IE9+. The error message "SCRIPT438:Object doesn't support property or method 'after'" appeared in the console. If a ...

What is the process for updating npm on a Windows operating system?

Seeking advice on upgrading my npm version, I attempted Option 3 for Windows as outlined in the npm documentation. However, upon installation, I received a message stating that npm.exe already exists in the nodejs folder. Despite trying to overwrite it u ...

How to retrieve the chosen row in an angularjs UI-GRID when the row selection event occurs

Within my application, I am utilizing a ui-grid and I am aiming to retrieve the selected row when a user chooses a row from the grid (where only one row can be selected at a time). I have successfully been able to obtain the selected rows through gridApi ...

Issue with displaying ajax response header with Jquery version 1.7.1

$.ajax({ async:false, type: 'POST', url: itemURL, success: function(data,status,jqXHR) { responseObj = data; console.log('success functi ...

Disable the div by graying it out when the button is clicked

In my jsni form, I have implemented a click handler on the save button. When the save button is clicked, I would like the specific div to be greyed out to indicate that data is being saved. var x=$doc.createElement("div"); x.id="nn"; var lbl=$doc.createEl ...

Finding a potential data breach in Node.js, MongoDB, and Chrome, exposed passwords are

My web app is built using nodejs with mongodb as the database backend, and I am encountering an issue with Chrome browser flagging my login process via passport.js as an exposed password. How can I prevent this warning? Should I implement something like Bc ...

A subtle X icon tucked away in the corner of the homepage, a result of the jquery modal window

Struggling with an issue on a client's website - there are multiple jquery sections with buttons that open modal windows. The problem is that the close button for these modals appears on page load and is situated at the top right of the homepage. Is t ...

Issue: EMFILE - exceeding maximum number of opened files

I'm currently working with nw.js, attempting to save images in an array of img tags with random names. However, I've encountered a few errors and I'm unsure what's causing them. for (i = 0; i < imgs.length; i++) { request(imgs[i].g ...

Alter the row's color using the selection feature in the module

Is there a way to change the color of a row when a specific property has a certain value? I found a solution for this issue on Stack Overflow, which can be viewed here: How to color row on specific value in angular-ui-grid? Instead of changing the backgro ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

Combining ng-if and ng-blur for effective coding

<input kendo-time-picker name="ArriveDateTime" class="form-control" k-format="'hh:mm tt'" k-parse-formats="['hh:mm tt']" k-ng-model="technician.ArriveDateTime" k-ng-disabled="!technicia ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Having trouble with removing the disabled attribute from an input file submit button

Currently, I am in the process of validating the file size and extension before it gets uploaded. My code is almost functioning perfectly, but there seems to be an issue with removing the disabled attribute from the submit button when the file meets all th ...

Exploring the differences between jQuery's methods for retrieving text, HTML, JSON

I'm feeling a bit perplexed: When I use the following code: $.get('http://externhost/somefile.js', callback, 'text'); I receive the error message: XMLHttpRequest cannot load http://externhost/somefile.js. Origin http://www.myho ...