What is the best way to send parameters to an angular service or factory?

This Plunker demonstration is a great visual guide: http://plnkr.co/edit/y3uacaQSc1MbrWKfb0At?p=preview

Here's the code snippet for reference:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = testFactory.testFunction;

});

app.service('testFactory',function(){

  this.testFunction = function(){
    alert(test_var);
  };

})

In the HTML section:

<body ng-controller="MainCtrl">
    <p ng-click="testFunction()">Hello {{name}}!</p>

  </body>

The current issue, as observed in the Plunkr example, is that `test_var` is undefined which is expected as it has not been defined. To resolve this, there is an intention to pass it from the controller without executing the function. However, directly assigning `scpe.testFunction = testFactory.testFunction(test_var);` results in immediate execution due to the parentheses. The goal here is to only pass `test_var` without triggering the function. How can this be achieved?

Answer №1

Enclose the call within a function to ensure that

testFactory.testFunction(test_var)
is executed only when $scope.testFunction() is called...

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope,testFactory) {
  $scope.name = 'World';
  var test_var = "iceland";
  $scope.testFunction = function() {
    testFactory.testFunction(test_var);
  };
});

app.service('testFactory',function(){

  this.testFunction = function(test_var){
    alert(test_var);
  };

})

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

Implementing communication between directive and controller in AngularJS by updating the changed value

Typically, the sequence of execution is controller ---> directive, isn't it? Here's a scenario I have: In the controller, we set the default value for placeholder: $scope.formsDropDown = { show: true, placeholder: 'Select a Form ...

using a function as an argument in the map method within a React component

I have a challenge where I am trying to display blog posts retrieved from my database. However, for each item, I also need to execute a download image function. I attempted to include the function within the .map function but encountered some errors. I am ...

How can I update the state with the value of a grouped TextField in React?

Currently working on a website using React, I have created a component with grouped Textfields. However, I am facing difficulty in setting the value of these Textfields to the state object. The required format for the state should be: state:{products:[{},{ ...

The challenge of validating md-select in Angular Material

Within my form, I have multiple md-select dropdowns with validation. Strangely enough, the validation is functioning correctly for all of the dropdowns except for one. This particular dropdown does not prevent the form from being submitted even when it is ...

A variety of personalized Vimeo play buttons

Recently, I stumbled upon a genius solution by Chris Coyier for creating custom Vimeo play buttons. It worked perfectly for my needs, but now I'm facing a challenge - how to make it function with multiple videos on the same page. I tried swapping out ...

Passing variables in Redirect() without exposing them in the URL; a methodical approach

After scouring the depths of the internet, I have been on a quest to figure out how to seamlessly redirect to a new page on my site while discreetly passing a variable without exposing it in the URL like so: www.test.com/?variable=dont.want.this.here I a ...

When utilizing Angular JS routing on localhost, the URL displays the filename

I am currently working on a website in Visual Studio 2010, using Angular and HTML code. When I debug the website in IE, the routing is functioning properly but the URL displays the file name "index.html" and "#" sign, like this: http://localhost:1349/D ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

Hiding BottomTabNavigator on specific screens using React Navigation (4.x)

Looking for a way to hide the bottom tab navigator specifically in the 'Chat' screen of my React Native and React Navigation app. Here is what I have so far: const UserNavigation= createStackNavigator({ Profile:{screen:Profile}, Search:{ ...

The dynamically generated table will only show the most recently added data

Currently, I am delving into the world of JavaScript to tackle an interesting challenge. Here's the scenario: I have a dropdown list populated with stream names derived from an array. Whenever a selection in this array changes using `onchange()`, I wa ...

Choosing a table cell in a React Bootstrap table

export class UsersTable extends React.Component { constructor() { super(); this.state = { data: null }; } componentWillMount() { fetch("http://localhost:8081/users/getData") .then(res => res.json()) . ...

Insert a JavaScript object into the rendered HTML using the componentDidMount lifecycle method

I'm trying to incorporate a JavaScript object into the template once the component has mounted for tracking purposes. Here is how I want the object to be rendered: var tracking = { pagename: 'page name', channel: 'lp&ap ...

Utilize AngularJS to sort through a JSON array and display the information in dual tables based on the array item

Recently, I came across some JSON data that looks like this: { "id": 2, "itemList": [ { "id": 7, "name": "xx", "extraInfo": "45", "tax": 21.00, "price": null, "oneTimeItem": false, "fkIdUserItem": 2, ...

Troubleshooting issues with rowspan in a Datatable

I am currently utilizing jQuery DataTables to display my grid data and implementing the rowspan concept with the rowsGroup option. Initially, it works well by spanning some rows and looking visually pleasing, but eventually, it starts failing. Here are so ...

Setting up server-side CORS in ExpressJS will not include the "Access-Control-Allow-Origin" header

Looking to tackle a CORS request for an ExpressJS server, which is new territory for me. Despite encountering similar issues in the past, I can't seem to pinpoint the problem this time around. It appears that the required headers may not be in the cor ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Using Javascript to save a numeric value and accessing it on a different webpage

I'm encountering an issue with a specific feature on my website. I want users to click on a hyperlink that will redirect them to an application form page. The challenge is ensuring that the reference number (a 5-digit code displayed as a header) is st ...

Update the dropdown field selection to the color #333 with the help of javascript

I am facing an issue with a dropdown field that has placeholder text and options to select. Initially, both the placeholder text and the options were in color #333. However, I managed to change the color of the placeholder text to light grey using the foll ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

What is the best method for capturing the line delimiter character(s) in a manner that is not dependent on the platform being

When using the regular expression /^\S+\s*$/m.exec("a\nb\n")[0], it only returns "a" without including the line delimiter, even though \s should match \n. After some experimentation, I discovered that modifying the expression ...