What is the best place for organizing AngularJS model logic?

In my app, I work with Shape POCO objects that are retrieved from an AngularJS ShapeService. These shapes have properties like width and height, and can be configured to maintain their aspect ratio. When one dimension changes, the other needs to be automatically adjusted to keep the ratio intact. The question is, where should this logic be implemented? One option is to have it in the Shape object itself, but figuring out how to enforce it is a challenge.

Should the Shape object handle this rule internally? If so, how can it be done? Is it the responsibility of the service instead? How can this be achieved without using $watch in the controllers model? Are there any alternative methods that I'm overlooking?

Answer №1

To simplify this process, it's best to have the Shape object enforce the rules itself. After all, that's what a Shape is designed to do, as you pointed out.

The challenge lies in how to empower the Shape to implement these rules. This largely depends on the nature of the Shape and its characteristics.

If the Shape is a POJSO (Plain Old JS Object), there is no built-in mechanism for enforcement.

shapeA = {width:10,height:20,enforce:true}

This means nothing prevents someone from bypassing the enforcement with a line like shapeA.width = 20 and disregarding the intended restrictions.

In a secure es5 environment where getters and setters/Object.defineProperty can be utilized, enforcing constraints such as aspect ratio becomes feasible. Modifying one value like shapeA.width = 20 can trigger an internal method within the object to uphold the desired properties.

For scenarios without ES5 support, explicit setters can be assigned to the object:

shapeA = {getWidth:function(){...}, setWidth: function(){...}, /* etc. */ }

This approach may not be aesthetically pleasing but serves its purpose effectively.

An alternative option could involve handling enforcement within the ShapeService using functions.

Allowing flexibility at input but enforcing rules upon saving is another possibility, though potential errors may linger until the save action is initiated.

Another suggestion could entail utilizing the controller and $scope.$watch, although monitoring numerous Shapes in this manner might not be ideal, as this logic doesn't truly belong in the controller.

In summary, a cleaner solution would be preferable. Perhaps limiting support to environments compliant with es5 standards could offer a more streamlined approach? :-)

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 is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

JavaScript: Various Outputs Depending on Input

There seems to be a discrepancy in the results when I input "coup," "cou," and then "coup." Can anyone offer insight into why this might be happening? To view my code on jsfiddle, click here: jsfiddle.net/xbuppd1r/43 var data = {"cards":[{"$type":"Assets ...

Steps for creating a file selection feature in Chonky.js

I recently integrated the Chonky library into my application to build a file explorer feature. One challenge I am facing is figuring out how to select a file and retrieve its unique ID when the user double clicks on it. const [files, setFiles] ...

Stopping setinterval on click can be achieved by using the clearInterval function in

I've encountered an issue while using a slideshow on my website. The plugin I'm using does not have an autoplay feature, so I had to implement it using setinterval in my code. Below is the code I used: var myInterval, startInt = function(){ ...

How to select a child element within a sibling div of a parent div using jQuery

HTML <div class="container-fluid"> <div class="input-page">...</div> <!-- field 1 --> <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div> <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> ...

Tips for Updating an item array in typicode/lowdb file database

Greetings, I am currently experimenting with an express app that utilizes a typicode/lowdb json file as its database. However, I am encountering difficulties with getting the update function to work properly. Below is an example of the code: The typicode/ ...

decoding json field containing forward slashes using javascript

Seems easy enough, but I'm having trouble figuring it out. let data="[{name:\"House\",id:\"1\"},{name:\"House and Land\",id:\"5\"},{name:\"Land\",id:\"6\"},{name:\"Terrace\",id:&bs ...

Tips for displaying indentations on Tube Geometry using THREE.js

Currently, I have a project where I am tasked with displaying dents on a pipeline in a 3D format. To create the pipeline, I utilized THREE.js's tube geometry which is illustrated below: <!DOCTYPE html> <html lang="en"> <head> ...

Can data be presented in AngularJS without the use of scope variables?

I have a method: <span ng-init="getJobApplicantsList(jobId)">(number should be display here)</span> Is there a way to display the data without having to store it in a scope variable? I need to use this method in many places. This is my cont ...

Retrieve the API array index by checking the value of the 'Name' field

I am looking to compare the name of a button I click on with an array in order to find the matching name and then select the corresponding array number. Currently, I have a For loop that retrieves information from every team in the array, but I only requi ...

What is the best way to extract the elements within a form using Angular and automatically add them to a list?

Recently, I started learning Angular and decided to create a simple list feature. The idea is to input an item name and price, then click "Add item" to see it added to the list below. I have all the code set up correctly, but for some reason the name and ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Need help with updating React component state within a Meteor.call callback?

I've constructed this jsx file that showcases a File Uploading Form: import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class UploadFile extends Component { constructor(){ super() this. ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

JavaScript code that loads a specific DIV element only after the entire webpage has finished loading

How can I ensure that the DIV "image" is loaded only after the entire page has finished loading? What JavaScript code should I use? <div class="row"> <div class="image"> CONTENT </div> </div> I plan to execute the functio ...

When the datepicker fails to display the chosen date (month) in the datepicker interface

I integrated momentjs datepicker into an AngularJS directive. I am facing an issue where the selected date is not displayed in the datepicker when expanded. For instance, if I select 05/05/2014 and then click submit, upon expanding the input to view the d ...

Displaying elapsed time in JavaScript (Node.js)

Looking for a way to convert a date time or time-stamp format like 2015-12-18 07:10:54 into a relative time, such as "2 hours ago." I attempted the code provided, but it seems to consistently show an incorrect estimation of "8 days ago." function convert ...

Can you explain the distinction between Array() and [] in Javascript, and when would it be preferable to use one over the other?

Similar Question: Understanding the difference between "new Array()" and "[]" in JavaScript array declaration When working with JavaScript, you have the option to create a new array using: var arr = new Array(); or simply using: var arr2 = []; Wha ...

Executing JSON.parse with embedded functions

There is a string that functions correctly when converted to an OBJ. var obj = JSON.parse('{ "placeholder": "Hello...."} '); This object is then used in the tagEditor plugin like so: $('textarea').tagEditor(obj); However, the require ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...