Utilize getters and setters with angular.extend and $scope in Angular development

I stumbled upon an interesting article AngularJS: Tricks with angular.extend(), which delves into the usage of `getters` and `setters` in conjunction with `extend`. However, there are certain aspects that leave me puzzled.

Js:

app.controller('ThingController', [ '$scope', function($scope) {

    // private
    var _thingOne = 'one',
        _thingTwo = 'two';

    // models
    angular.extend($scope, {
        get thingOne() {
            console.log("get thing1");
            return _thingOne + 'eeeeee';
        },
        set thingOne(value) {
            console.log("set thing 1");
            if (value !== 'one' && value !== 'two'){
                throw new Error('Invalid value ('+value+') for thingOne');
           }
        },
        get thingTwo() {
            console.log("get thing2");
            return _thingTwo + 'oooooo';
        },
        set thingTwo(value) {
            console.log("set thing 2");
            if (value !== 'two' && value !== 'three'){
                throw new Error('Invalid value ('+value+') for thingTwo');
           }
        }
   });

    // methods
    angular.extend($scope, {
       get things() {
            return _thingOne + ' ' + _thingTwo;
        }
    });

}]);

Html:

<body ng-controller="ThingController">
    {{ things }} // one, two 
</body>

My queries:

  1. Why isn't oneeeeeee returned from get thingOne()? What about get thingTwo()?

  2. Where exactly is set thingOne called, and the same for set thingTwo? I couldn't find any output like set thing 1 or set thing 2 in the console.

  3. How can I define a set method within the angular.extend methods? Is it feasible to assign a value from the view?

Answer №1

Here's an alternative approach:

angular.merge($scope, {
    fetch items() {
        return $scope.itemOne + ' ' + $scope.itemTwo;
    }
});

The setter will be triggered with this example:

$scope.itemOne = 'sample';

Answer №2

Property accessors, not related to angular.extend, offer the ability to incorporate logic into reading and writing object fields.

To define a property accessor:

var instance = {
   get prop() { return this._prop },
   set prop(value) { this._prop = value }
}

Usage example:

instance.prop = "new value"
var x = instance.prop

angular.extend simply copies this definition to $scope. Alternatively, you can utilize Object.define, demonstrated here: http://jsfiddle.net/v1bxyrx1/2/

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

Maximizing the efficiency of Java Script code

I am struggling with optimizing this JavaScript code that adds and removes classes based on the presence of a specific class in the next rows of a table. Can anyone provide some guidance on how to make this code more efficient? $(".showTR").click(functi ...

Shifting around haphazardly positioned crates using the cursor

I've successfully developed a program that fills the canvas with randomly positioned boxes of various colors. While this task was relatively easy, I'm now facing a challenge in moving these colored boxes around using my mouse. Additionally, I wan ...

What is causing the Uncaught TypeError when invoking a private JavaScript ES5 class?

My goal is to create a JavaScript class using ES5 syntax. However, I encountered an error when calling one method from another, which displays the following message in the console: Uncaught TypeError: root.abLog is not a function The relevant code snip ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

When using node.js, the initial request yields no response while the subsequent request provides the expected data

Currently, I am in the process of setting up a node.js API using Express, Body-parser, and MySQL. An issue I am encountering is that when making a GET request to a route for the first time, it returns blank. However, on the second attempt, it retrieves th ...

choose user by ticking the checkbox

For each user in the table, I aim to create a checkbox. Here is my tableBody: <TableBody> {users.map((user) => { return ( <TableRow key={user.id}> <TableCell padding="checkbox"> <Checkbox ...

Attempting to create a lineup of bricks with varying widths that are directly related to the overall width of the canvas

I'm attempting to create a row of randomly sized bricks on a canvas. The bricks should have varying lengths, but must stay within the confines of the canvas. The canvas has a length of 400, and I want there to be a 10px padding on each side between ...

Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property? items() { return this.table.filter.keyword ? this.dataArray.filter( item => item.nombre.toLowerCase().includes(t ...

What impact does incorporating a new test case have on code coverage in Jest?

I recently encountered an unexpected situation while working on a Jest test suite. Despite not making any changes to the codebase, I simply added a new test. Originally: mylibrary.js | 95.65 | 89.66 | 100 | 95.65 | 54-56,84 ------------ ...

Encountering the error message "Uncaught Promise (SyntaxError): Unexpected end of JSON input"

Below is the code snippet I am using: const userIds: string[] = [ // Squall '226618912320520192', // Tofu '249855890381996032', // Alex '343201768668266496', // Jeremy '75468123623614066 ...

Error in Vuejs: Property '_withTask' is undefined

I am attempting to dynamically add new HTML elements to my div upon button click, using v-for. However, I encounter an issue where the element (article) is added successfully on the first click, but subsequent clicks result in an error. vue.js?3de6:1743 ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

Utilizing MochaJS, Supertest with Babel, Browserify, and Gulp to run Travis-CI

After watching tutorials and webcasts on Code School, focusing on Node, ES2015, Angular, and Express, I decided to work on my own project. I have successfully implemented all of the above technologies. Currently, I am attempting to set up automated builds ...

Interactive canvas feature in a browser window with scrolling capabilities (drag and drop functionality)

One challenge I'm facing is when drawing in a canvas on a browser window that has a vertical scrollbar. The figures are in the correct position, and it's possible to interact with them by grabbing and making connections. However, this interactio ...

Next.js - With shallow routing for dynamic paths, the browser URL no longer includes the base path

My website utilizes dynamic routes for Pages named [name] and [brandid]. The browser URL structure is expected to be based on [basePath]/[name]/[brandid]. However, after implementing shallow routing with the code snippet router.push("?page=2", ...

"Implementing a conditional statement in JS / JQuery without the need to

I'm interested in finding out if it's possible for a function's conditional statement to display the result whenever the argument is true, without needing to call the function again. Here is an example of such a statement: if($('#a&ap ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

What is the best way to implement a nested lookup in MongoDB within a field?

Within my database, I have a collection named Randomhospital. Inside this collection, there is a field named hospital structured as follows: { "id": "GuDMUPb9gq", "Hospital Name": "UPHI", "Hospital City&qu ...

The Vue property or method is unrecognized when utilizing the non-minified version

When I attempted to display the name 'John' using an inline template in a simple Vue example, I encountered the following error message: [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. ...

Tips for transmitting a querystring through RegisterStartupScript?

I am facing a situation in my code behind where I need to access the value of event.id in order to open a modal window and edit the event. The issue is that when setting it as a querystring parameter, 'event.id' is being treated literally instead ...