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

Tips for generating AJAX requests directly from HTML documents

Hey there! I'm fairly new to JavaScript and have a question that might seem silly to some. How exactly can I invoke a function from a Coffeescript file within my HTML code? I'd like to give users the option to choose the language in which they v ...

Top technique for extracting json files from post requests using nodejs

Situation: I'm running a Node.js REST server that receives JSON files, parses them, and inserts them into a database. With an anticipated influx of hundreds of requests per second. Need: The requirement is to only perform insertions by parsing the JS ...

What could be causing the resolve method to not send any data back to the controller?

While following a tutorial on YouTube, I encountered an issue with incorporating the resolve method getposts into the contactController. Despite my efforts, no value is being returned. I've spent hours searching for answers on Stack Overflow to no av ...

Every time I try to utilize "useCallback," it results in a TypeError error popping up

I am struggling with an issue related to a const experience that involves creating 6 experiences with their respective popovers. I have been instructed to use useCallback, but every time I attempt to do so, I encounter an error message. This relates to my ...

Effortlessly sending multiple forms on a single page via POST in Express JS without the need for page refresh

I am creating a new application using ExpressJS and I want to include the following HTML code in a jade file. On one of my pages, I have 4 form buttons: <div class="dog"> <div class="dog_wrapper clearfix"> <div cla ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

Initializing an HTML5 video player directly from an Array

I am trying to populate a video player on my webpage with an array of videos. Here is the code I have so far: var current = 0; var videos = ["01", "02", "03", "04"]; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomInde ...

Easily linking a React app to MongoDB

I recently developed a basic react app using 'create-react-app'. The app includes a form, validation, and Bootstrap components. It may not be extravagant, but it functions flawlessly. Furthermore, I registered with MongoDB to obtain a compliment ...

Utilizing REST-API with Angular 2 and Electron

I am encountering an issue with my Electron App that utilizes Angular 2. I had to make a modification from <base href="/"> to <base href="./">, which is a relative path within the file system, in order to make it function properly. However, thi ...

Automatically populate fields with pre-filled information

In my database, I have a table named "Produits": public function up() { Schema::create('produits', function (Blueprint $table) { $table->id(); $table->string('reference')->nullable(); ...

What is the best way to target the shadow DOM host element specifically when it is the last child in the selection?

I want to style the shadow DOM host element as the last child. In this particular situation, they are currently all green. I would like them to be all red, with the exception of the final one. class MyCustomElement extends HTMLElement { constructor() ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

What is the best way to add <li> elements dynamically in an AngularJS application?

I am dealing with html code similar to this: <ul class="list"> <div ng-repeat="avis in avisData"> <li id="li"> <a class="item item-thumbnail-left" href=""><img src=data:image/jpeg;base64,{{avis.image ...

`Discover the latest version of Tailwind using JavaScript or PHP`

My setup includes Laravel v8.81.0 (PHP v8.1.2), Vue v3.2.30, and Tailwind https://i.sstatic.net/fVbJB.png I am looking to fetch the Tailwind version in JavaScript similar to how I can get the Vue version using: //app.js require('./bootstrap'); ...

Setting the expiry time for vue-cookie in hours Would you like to learn

I'm currently using the following code to set a 3-hour expiry for my vue-cookie: VueCookie.set('S3ID', getS3ID, 3); However, it seems that this function is actually setting the cookie expiry time as 3 days instead of 3 hours. Can anyone ex ...

Importing textures and loading mtl files in Three.js from various web addresses

Something strange is happening with my Roblox API integration. I'm trying to retrieve the OBJ file, MTL file, and Texture file using the API. The main API link I have is https://t2.rbxcdn.com/ef63c826300347dde39b499e56bc874b, which leads me to two cru ...

How do I integrate a button into my grey navigation bar using tailwindcss in REACT?

Is it possible to integrate the - button into the gray bar? I am encountering an issue where my blue button extends beyond the borders of the gray bar in the image provided. export default function App() { ... return ( <div className="text-md fon ...

Guide on utilizing Nextjs middleware for directing users to sub-domain according to their IP address

I've been struggling to effectively implement NextJs's middleware for redirecting users from a specific country to another web domain. I've encountered some issues with my setup: Main domain: https://www.example.com sub-domain: src/middle ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

Differences between importing Component and Vue from "vue-property-decorator" versus importing Vue from "vue"

Can you explain the specific differences and scenarios where importing Vue from vue-property-decorator versus just vue would be applicable? I have learned that when defining a custom component with a @Component decorator, it is necessary to import Vue fr ...