Using JavaScript/Angular to borrow a function and add additional parameters

In my scenario, I have a service function that requires a static parameter and a second custom parameter that changes based on the controller it is being used in. I am looking for a way for my controller/view to invoke this service function without having to create a specific method in the controller just to pass that custom parameter. I'm uncertain whether this approach involves currying, call, bind, or apply.

.service('ExampleSvc', function() {
  this.call = function(param, controller) {
    console.debug(param, controller);
  }
})

.controller('FirstCtrl', function($scope, ExampleSvc) {
  $scope.call = ExampleSvc.call; // something magical happens here

  // avoid repetition
  $scope.call = function() {
    ExampleSvc.call('staticParam', 'FirstCtrl');
  }
});

.controller('SecondCtrl', function($scope, ExampleSvc) {
  $scope.call = ExampleSvc.call; // something magical happens here

  // avoid repetition
  $scope.call = function() {
    ExampleSvc.call('staticParam', 'SecondCtrl');
  }
});

Answer №1

It seems like you want to access a service in the view, so the simplest way is to assign the service to a $scope variable:

$scope.service = $service;

This way, every method from the service can be directly called from the view without needing to create any special $scope methods.

If only one specific method needs to be called with different parameters, you could do:

$scope.call = function(){ ExampleSvc.call.call(this,'param', 'FirstCtrl'); };

In this case, an anonymous function is created to call the call method with the desired parameters.

However, if the service varies with each usage, a better approach would be to return it in the service constructor. This allows for creating a new object of the service each time by using the new keyword.

//service code

return function(controller){

  this.controller=controller;

  //methods here ...

};

//controller code

$scope.service = new service("ControllerName");

With this approach, different service objects can be used for each instance, avoiding the singleton pattern typical of services. An example implementing this approach is shown below:

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

app.controller("cont1",function($scope,person){

  $scope.p = new person("Tom","Hanks");
  
});

app.controller("cont2",function($scope,person){

  $scope.p = new person("Will","Smith");
   
});

//our service which returns constructor
app.service("person",function(){

  return function(name,surname){
    
    this.name = name;
    this.surname = surname;
    
    
    this.getName = function(){
    
      return this.name;
      
    };
    
    this.getSurname = function(){
    
      return this.surname;
    };
    
  };
  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  
  <div ng-controller="cont1">
  
      <span> Person is: <b>{{ p.getName() }} {{ p.getSurname() }}</b></span>
  </div>  
  
  <div ng-controller="cont2">
      <span> Person is: <b>{{ p.getName() }} {{ p.getSurname() }}</b></span>
  </div>  
  
  
</div>  

This approach allows for using the service in a flexible manner by creating new objects. Assigning it to scope enables running the configured object directly there.

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

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

Exploring LZMA compression in conjunction with next.js

Is anyone familiar with using the lzma algorithm to compress video, photo, text, etc. in the Next.js framework? I have searched everywhere but couldn't find a solution. I haven't found a proper demonstration or answer anywhere. I would greatly a ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...

Having trouble invoking an established route within a different route in an Express JS project

While working with an Express JS application connected to a mySQL database, I encountered an issue when trying to fetch data from a pre-defined route/query: // customers.model.js CUSTOMERS.getAll = (result) => { let query = "SELECT * FROM custo ...

Is it possible to prevent the selected option from being available in other select lists using AngularJS?

Can anyone help me figure out how to disable an option in one select list when it is selected in another using AngularJS? I have set up a select list for From Year and To Year with ng-repeat, which is working fine. Now, I just need to implement the functio ...

Retrieve the computed value of a cell in an Excel spreadsheet using Node.js

Utilizing node.js in tandem with the exceljs module to process my Excel sheets. Writing values into specific cells while others already contain formulas. Seeking a method to trigger those formulas and programmatically store the resultant values in the she ...

AngularJS REST Network Error: The server has refused the request with error code 405,

During my experience with AngularJS, I successfully utilized the following function: $http.get( "fruits.json" ).success( $scope.handleLoaded ); I now have the desire to switch this from a file reference to a URL (which outputs JSON using Laravel 4): $ht ...

Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countrie ...

An easy guide to sorting outcomes using JSON

I have JSONResults in my Controller that contains all the data from a table. On the client's HTML detail view page, I am using JavaScript to fetch this data. How do I extract data from JSON where the client name is equal to klID (this is a JSON string ...

Why does the node.js app only run from the command prompt and not directly?

I have a basic vbscript that launches two nodejs apps necessary for my server's operations. Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "node C:\!webroot\site.name\server\pubsub.js" objShell.Run ...

Having trouble grouping data on website due to duplicate names

Currently in the process of scraping data from various websites and looping through it. Specifically focusing on scraping the head section. This is an example illustrating the structure of the data: const head = { rel_data: [ { rel: &quo ...

Combining the elements within an array of integers

Can anyone provide insight on how to sum the contents of an integer array using a for loop? I seem to be stuck with my current logic. Below is the code I've been working on: <p id='para'></p> var someArray = [1,2,3,4,5]; funct ...

CSS grid challenges on a massive scale

My CSS grid timeline is currently generating around 1300 divs, causing performance issues. Is there a way to style or interact with the empty nodes without rendering all of them? I also want each cell to be clickable and change color on hover. Any suggest ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

Is there a workaround using jQuery to enable CSS3 functionality across all browsers?

Is there a way in jQuery to make all browsers act as if they have CSS3 capabilities? ...

Exploring the use of v-model in Vue3 child components

After some exploration, I recently discovered that in Vue3, the v-model functionality does not work responsively or reactively with child Component. The following code snippet showcases how the username data gets updated: <template> <div> ...

Endless scrolling dilemma

I came across an example of infinite scrolling and attempted to implement it myself. Despite correcting all the errors I could find, it still refuses to work. Below is the directive code: module.exports = /*@ngInject*/ function scrollDirective($rootScope ...