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

AngularJS Currency Converter - Converting Currencies with Ease

I have a question regarding the most efficient way to handle currency conversion on a webpage. Currently, I have multiple input fields displaying different currencies. When a user clicks on the currency conversion button, a modal popup appears. After the ...

The autoplay feature for YouTube videos is not functioning on Chrome when viewed on an iPhone

if($('.explore-video-btn').length > 0) { var video_id = youtube_parser($('.explore-video-btn').attr('data-video-url')); } var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api" ...

The commands 'npm run watch' and 'dev' are no longer functioning on my computer for my Laravel project. I am encountering an error stating: '[webpack-cli] RangeError: Maximum call stack size exceeded'

Recently, while working on a Laravel website, I've been focusing on writing JavaScript code to integrate Meilisearch. To facilitate this process, I incorporated the 'dotenv' library with node to access variables from my .env file for securit ...

Transferring information from server/app.js to Angular-fullstack controller with multer

I'm facing an issue transferring a filename from server/app.js to a controller in client/app/ Currently, I am utilizing Multer for handling file uploads, which is functioning correctly. However, I need to transfer the filename back to the client side ...

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...

Efficiently centering content in a grid layout using automatic fit repetition for optimized responsiveness

I've implemented a responsive grid where each item has its own hidden details section that is revealed upon clicking the item. The structure of the HTML/CSS setup is as follows: <div class="grid"> <div class="item"> ...

Error: Google Chrome encountered an unexpected token } that caused a syntax error

I encountered an error that reads: Uncaught SyntaxError: Unexpected token } This error only appears in Chrome, while other browsers like Mozilla and IE do not show it. Here is my script causing the issue: <script type="text/javascript" language="jav ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: https://i.sstatic.net/IxcnK.png HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-oute ...

Experience seamless one-to-many broadcasting with WebRTC/Kurento, featuring server-side recording capabilities

I am currently exploring Kurento to determine if it fits my needs. I am interested in developing a mobile application that can record and stream video to a server in real-time, with the server saving the video on its file system as it is being transmitted. ...

necessity for a condition in Material UI input field

I need assistance with a function that I use to incorporate Material UI text fields into my code. The issue I'm currently facing is figuring out how to dynamically add the "required" attribute based on a boolean parameter that determines whether the f ...

Retrieve the HTML tags following the modification of my information in ASP.NET

Apologies for any language errors, I am new to asp.net development. 1- I have a table with dynamically created rows and columns based on user selection of row and column numbers. 2- Each row in the table has the following controls: A- One textbox, one l ...

Is there a way in JavaScript or jQuery to display text from an array and switch to the next piece of text in the array with the click of a button?

I currently have an array containing 13 items, all of which are text. To display the text from the array, I am using: document.write(arrayname["0"]); However, I would like to implement a functionality where users can click a button to fade out the curren ...

How to preselect an item in a RadioGroup

We are facing a challenge in setting a default value automatically for a RadioGroup upon page load. Despite the documentation mentioning a defaultValue property (https://material-ui.com/api/radio-group/), it does not seem to work as expected. We experimen ...

Using React, a link to the same component is created, but a subcomponent is mistakenly using an outdated version of

Here, we have a SubComponent and a MainComponent created to showcase an image collection. The Subcomponent allows you to toggle between pictures in the collection using the onclick() event. The MainComponent also includes links to other collections, which ...

Can an infowindow be automatically closed based on specific criteria?

Show the infowindow only when hovering over the marker. It should disappear when moving the mouse away from the marker. The infowindow should stay open only if you click on the marker, and can be closed by clicking the close button on the infowindow. ...

What is the process for assigning an element to a specific URL ID?

Imagine having an array of objects structured like this: [{ details: {id: 7}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: 8}, type: minigame1, ...(more values that need to be accessed later) }, { details: {id: ...

Presenting charts using flot library

Having Trouble: My x-axis ticks are not displaying correctly on the graph - only the first tick is showing at the far right and no bars are being plotted. I believe I might be overlooking something obvious. Desired Fix Needed: Display all x-axis ticks and ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

What exactly is the purpose of the script type importmap?

Can you explain the role of <script type="importmap"> and why it has become necessary for my code to function properly? <script type="importmap"> { "imports": { "three": "http ...