transfer scope variable to scope function

I notice this pattern frequently

view:

<input ng-model="vm.model">
<button ng-click="vm.method(vm.model)"></button>

controller:

function Controller() {
    var vm = this;
    this.method = function(parameter) {
       // perform actions with the model passed as parameter.
       // even though it could be accessed directly by vm.model
}
}

Alternatively, this would also work :

<input ng-model="vm.model">
<button ng-click="vm.method()"></button>

Is it considered a bad practice for methods in the controller to access variables in the same scope without passing them as parameters?

Answer №1

It can be considered acceptable to directly access the scope variables within a method without passing them as parameters.

If the method is generic and used by multiple buttons, it may be more appropriate to pass the variables as parameters.

An example of this would be when dealing with various combinations of source and target listboxes, where items need to be moved between them using the same method with different parameters for each pair.

Answer №2

Depending on your specific design, it may be more advantageous to pass a parameter rather than directly accessing a scope variable in order to create a method that is reusable.

This approach can be particularly helpful when managing multiple views within a controller.

For example, consider a ModelController responsible for CRUD operations, with separate create, edit, and list views.

Create View:

<input ng-model="vm.model">
<button ng-click="sharedMethod(vm.model)"></button>

Edit View:

<input ng-model="vm.model">
<button ng-click="sharedMethod(vm.model)"></button>

List View:

<div ng-repeat="vm in vmList">
    <input ng-model="vm.model">
    <button ng-click="sharedMethod(vm.model)"></button>
<div>

Answer №3

Adhering to this principle, it is recommended to always explicitly call functions with parameters from the template.

Let's illustrate this with a simple example.

var vm = this;
this.method = function(parameter) {
  //It's clearer that the function expects a parameter.
  if (parameter) { //do something } 
}

Advantages of Using Parameters:

  1. Testability: Code that can be tested is typically more readable and easier to maintain in the long term.
  2. Independence: This approach allows the function to be reused by various controllers, services, etc., as it does not rely on a specific scope structure.

The sequence of ng-model and ng-click execution can be uncertain. Instead, consider using ng-change or creating a $watch on the $scope to ensure accurate model variable values.

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

Refreshing a Next.js page results in a 404 error

I've set up a Next.js page called page.js that can be accessed through the URL http://localhost:3000/page. However, I have a need to access this page through a different URL, namely http://localhost:3000/my-page. To achieve this, I decided to utilize ...

The image slider script I've built is functioning perfectly in Codepen, but unfortunately, it's not working as

My image slider called Orbit is functioning properly on Codepen.io, however when I try to run the exact same code on Plunker, it doesn't work at all. <ul class="slider" data-orbit> <li> <img src="http://foundation.zurb.com/docs/a ...

Extract information from one webpage, proceed to the following page, and repeat the process, utilizing JavaScript on the site

Exploring various web scraping techniques, I've hit a roadblock and could use some assistance. Currently, my Python code successfully extracts data from the first page of my website. response = requests.get(url) soup = BeautifulSoup(r.text, 'ht ...

Angular's Restangular initiates a blank promise at the beginning

One of the services I created can fetch data from the server and cache it, or retrieve data directly from the cache. The code snippet below illustrates this functionality. While using .then statements in the client side for cached data, I've noticed ...

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...

Issue with vue-apollo package causing GraphQL query not to display on the frontend

Currently, I am expanding my knowledge of GraphQL and working on a project where I aim to display queries in the front end. To achieve this, I have incorporated the package GitHub - Akryum/vue-apollo: ...

The server mistakenly sent the resource as a Stylesheet even though it was interpreted differently

Dear Fellow Coders, Could anyone lend a hand? I encountered this issue on my website after uploading it to my FTP: "Resource interpreted as Stylesheet but transferred with MIME type text/plain" </head> <body> <div class= "navbar navbar ...

Utilize data from two distinct JSON sources that are updated at varying intervals, and display the combined results in an ng-repeat

I am currently working on creating a status list that pulls data from two separate JSON sources. The main purpose of this list is to show general information from the first source, while also indicating a status color based on the number of people in the s ...

Tips for displaying a React component with ReactDOM Render

_Header (cshtml) <div id="Help"></div> export default class Help { ReactDOM.render( <Help/>, document.getElementById('Help') ); } Help.js (component) } My objective is to di ...

What is the best way to add all IDs to an array, except for the very first one

Is there a way to push all response IDs into the idList array, excluding the first ID? Currently, the code below pushes all IDs to the list. How can it be modified to exclude the first ID? const getAllId = async () => { let res = await axios({ m ...

The content within an iframe is inaccessible through JavaScript when the onload event occurs

My current project involves integrating a payment service provider with 3Ds, and one of the steps in the process requires following specific instructions: Upon receiving the response to your initial API request, extract an URL along with some data. Embed ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

Show the textbox automatically when the checkbox is selected, otherwise keep the textbox hidden

Is it possible to display a textbox in javascript when a checkbox is already checked onLoad? And then hide the textbox if the checkbox is not checked onLoad? ...

Receive information from the server and display it on the front-end

Hello! I'm currently in the process of developing a video uploader for my website. So far, I've successfully been able to upload videos from the front-end (built with React.js) to the back-end public folder (using Node.js) through the POST method ...

Dealing with undefined properties in Javascript can cause errors

[ { dateTime: '2016-03-30 05:55:53', value: '4.0' }, { dateTime: '2016-03-30 05:55:55', value: '17.0' }, { dateTime: '2016-03-30 05:55:57', value: '17.0' }, { dateTime: '2016-03-30 06:0 ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

Uncertain about navigating the Ionic update

I have been actively working with Ionic 3 on multiple projects, but now I find myself in a position where upgrading to Ionic 5 is necessary to stay current. The process of upgrading to Ionic 5 seems daunting as it requires significant rework of my existin ...

Accelerate Image Preloading速

I am currently in the process of creating a website that features divs with background images. Although I am new to JavaScript, I am eager to learn more about it. My main goal is to preload these images so that visitors do not encounter any delays or bla ...