Understanding the implementation of setters in JavaScript: How are they utilized in Angular controllers?

After learning about getters and setters, I came across an example that clarified things for me:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith'
};

Object.defineProperty(person, 'fullName', {
    get: function() {
        return firstName + ' ' + lastName;
    },
    set: function(name) {
        var words = name.split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
});

This code is equivalent to:

var person = {
    firstName: 'Jimmy',
    lastName: 'Smith',
    get fullName() {
        return this.firstName + ' ' + this.lastName;
    },
    set fullName (name) {
        var words = name.toString().split(' ');
        this.firstName = words[0] || '';
        this.lastName = words[1] || '';
    }
}

person.fullName = 'Jack Franklin';
console.log(person.firstName); // Jack
console.log(person.lastName) // Franklin
  1. The question arises when we see:

    person.fullName = 'Jack Franklin';

    How does the equal sign trigger the setter method?

  2. 2.

Looking at this snippet from an Angular program:

var phonecatApp = angular.module('phonecatApp', []);

phonecatApp.controller('PhoneListCtrl', function ($scope, $http) {
  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data;
  });

  $scope.orderProp = 'age';
});

When we declare or call functions with parameters in Angular like:

function ($scope, $http) {...}

Is there a hidden getter mechanism at play behind the scenes in how those services are injected into the function?

Answer №1

Here are the responses to your queries:

1. How does the equal sign trigger the setter function?

The equal sign invokes the setter function that you have defined as part of getter and setter construct in ECMA language - refer to spec for details.

2. Does a getter come into play when declaring (or calling?) the function's arguments in this code snippet?

No, a getter is not utilized in this scenario. Angular typically uses the parameter names of functions to identify previously registered services for injection. Minifying the code by changing parameter names can cause issues, hence explicit annotation is recommended. The following two approaches demonstrate how explicit annotation can be done:

app.controller("Foo", FooCtrl);

FooCtrl.$inject = ["$scope", "$http"];
function FooCtrl($scope, $http){
}
app.controller("Foo", ["$scope", "$http", FooCtrl]);

function FooCtrl($scope, $http){
}

Answer №2

Within the phonecatApp instance provided, there are no property accessors being utilized; only raw properties are accessed.

To enhance it with property accessors and implement the controllerAs syntax, the revised code would appear as follows:

PhoneListController.$inject = ['$http'];
function PhoneListController($http) {

    var self = this;
    $http.get('phones/phones.json').success(function(data) {
        self._phones = data;
    }):

    Object.defineProperty(this, 'phones', {
        get: function() {
            return self._phones;
        }
    })

    Object.defineProperty(this, 'orderProp', {
        get: function() {
            return 'age';
        }
    }}
}
phonecatApp.controller('PhoneListController', PhoneListController);

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

What could be causing my post request to function properly in POSTMAN but not in my React application?

Here are my POSTMAN headers along with the settings I used to send my POST. It only started working when I switched the Content-Type to application/json. https://i.stack.imgur.com/Xz2As.png https://i.stack.imgur.com/aJtbD.png This pertains to the server ...

Once logged out in Vue Router, the main app template will briefly display along with the login component

After clicking the logout button, I am experiencing an issue where my main UI remains visible for a few seconds before transitioning to a blank page and displaying the login form component. This behavior is occurring within the setup of my App.vue file: & ...

Sharing information in React applications

I'm a beginner when it comes to using javascript and React, so I have a question regarding posting data from within a component. In my scenario, I am utilizing the fetch API for making POST requests. Below is the code snippet I have created: export f ...

Personalized JSON response type for AJAX requests

Do you think it's possible to achieve this? I have an idea to create a unique dataType called "json/rows". This new dataType would parse the server output text and manipulate it in some way before passing it to the success function. What do you think ...

Obtaining the total of all values in an object using ng-repeat

It seems like I might be overlooking a fundamental concept here, and I could really use some guidance. I have a set of data that appears like this: "playerPoints"{ "ted":{"military":3,"gold":2}, "bill":{"military":2,"gold":4} } I am using ng-rep ...

Leverage the controller's properties and methods within the directive

My situation involves a variety of inputs, each with specific directives: <input mask-value="ssn" validate="checkSsn"/> <input mask-value="pin" validate="checkPin"/> These properties are managed in the controller: app.controller("Ctrl", [&ap ...

Ways to retrieve the specified data in Javascript in string format

I'm facing an issue where the data I passed from a JavaScript array to a Java servlet and back to JavaScript is showing as "undefined." Check out my JavaScript code below: var buildingNumbers = []; // Let's assume the values of buildingNumbers ...

What is the purpose of using double % in Java or JSP?

Yesterday, while reviewing some code, I came across a line that seemed very peculiar to me. In a JavaScript function, there is a condition checking for a string passed as a parameter in the following manner: "%%unsubscribe%%". See the snippet below for re ...

CORS blocked the JavaScript Image's request

I am encountering an issue with my code that involves capturing selected divs using the HTML2Canvas library. However, when I try to download the captured image file, it is not working as expected. The error message I keep receiving is "Access to Image at ...

AngularJS drag-and-drop functionality for creating and rearranging lists

I am in need of a drag and drop list feature using angular, but the $scope.list must also be updated as I have to save the new order in my database. I came across this helpful answer and utilized it to create this http://jsfiddle.net/aras7/9sueU/1/ var m ...

A unique technique for creating a stunning visual effect with images using

Can anyone help me with this issue: Check out this animated GIF The images in my project are overlapping when scrolling! How can I achieve a similar effect for my images? Is there a tutorial or plugin available for this? Here is the current code sn ...

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

Struggling to make comparisons with numerical data from MongoDB in an ExpressJS route

I am currently developing a website using Node.js, EJS template, MongoDB, and Express. I am working on implementing search functionality on my page using forms, but I am encountering a small issue. The problem is related to a logical issue in the search f ...

Move two markers on Google Maps simultaneously

After researching various articles and posts on Stack Overflow about selecting multiple markers in Google Maps, I have been unable to find a solution for dragging two markers simultaneously. While I've managed to make it work so that one marker can tr ...

What is the correct placement for $.validator.setDefaults({ onkeyup: false }) in order to deactivate MVC3 onKeyup for the Remote attribute?

After coming across various solutions on how to disable the onKeyup feature of MVC3 Remote Validator, I noticed that many suggest using the following code: $.validator.setDefaults({ onkeyup: false }); However, I'm in a dilemma about where to place t ...

`The process of adding an element to the beginning of an array``

I find myself in this scenario: I am dealing with 2 array1 variables, defined as array1 = ["fruit","vegetables"]; and array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"]) T ...

What is the best way to implement an automatic logout feature in PHP?

I develop websites with login/logout functionality. Whenever a link or button is clicked on the website, I use an ajax function to verify the user's login status and automatically log them out if their session has expired. The logout function also up ...

What is the best way to showcase an ajax response on an HTML webpage?

Apologies for the length of the code, but I'm looking to condense it while maintaining the same functionality. Is there an alternative approach or method that could achieve the same results? I receive data from PHP, which is then passed to JavaScript ...

no such file exists in the directory

My current project involves connecting a javascript file to an html file using the <script> tag. However, upon rendering the html page, I encountered an error in the console indicating that the javascript file could not be located. Here is the struc ...

Analyzing Dynamic Content

Currently, I am engaged in content parsing and have successfully executed a sample program. To demonstrate, I have utilized a mock link which you can access below: Alternatively, you can click on this link: Click Here In the provided link, I have parsed ...