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

Upgrade from AngularJS to Angular 5 in Eclipse

Currently, I have a web application built in AngularJS, but I am looking to transition it to Angular 5. The existing webapp is running on Eclipse with a Tomcat server and has Java as the backend language. I have created a new version of the web applicati ...

The Guide to Utilizing Autonomous Models in Directive

Hey there! I have a question regarding a radio button directive. In this directive, I pass a model for the collection that will be set to the selected radio button. var app = ChartsModules.getInstance().getModule("amkaiCharts.directives"); ...

Identify the class within a child division and include the class in a separate division

How can I detect a special class within a child div and then add a class to another div when that specific class is found? For example: <ul class="m-a-ul"> <li class="menu"> </ul> Now, if the class collapsed is dynamically added: ...

The error callback encountered {"readyState":4,"status":200,"statusText":"success"} while processing

When I make a call to this url, the response is a JSON object when done directly in the browser. However, when I try to do it via ajax using the following code snippet: $.ajax({ url: url, type: "GET", dataType:"jsonp", succ ...

Requesting a resource using the HTTP GET method returned no data

Looking to process the response from an http-request using JavaScript? Check out this straightforward example below. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html x ...

Trouble with implementing an onclick event listener in a foreach loop

While generating and adding HTML in a for loop, I noticed that adding onclick events within the same loop is not functioning correctly: items.forEach(item => { itemHtml = `<div class="${item.id}">${item.id}</div>`; $(".it ...

Scrolling back to the top of the page using Jquery instead of a specific div

Check out the code for my project here. The isotope feature is functioning correctly, however, when clicking on the image, instead of scrolling to the navigation under the red box as intended, the page scrolls all the way to the top. If I modify the follo ...

Using the AngularJS directive with $http to handle JSON responses

Following the steps mentioned here I am using Ajax to retrieve server data which is in Json format containing markup with a directive. I am attempting to use $compile to trigger this directive, but so far, I have been unsuccessful. Below is the controlle ...

Creating distinctively tinted vertices for every subdivision step is simple with the following technique

I am currently working on an application that utilizes different standard geometries, such as box geometry. The application can apply up to 5 levels of subdivision on the original geometry. I am facing challenges in coding a color-coding system for the ver ...

Leveraging the power of HTML 5 to dynamically insert content into a jQuery table

I am experiencing an issue with my jquery stock ticker. It displays the latest stocks including Company Name, stock price, and percentage changed. The stock price can be in GBP, USD, or YEN, but the current ticker does not indicate the currency. I attemp ...

Icons in Semantic-UI: Facing Difficulty in Accessing ("CORS Request Not HTTP"

Here's an example I'm working on: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Understanding - Main</title> <link rel="stylesheet" type="text/css" href="../semantic/dist/semanti ...

My form does not receive the Bootstrap classes when using the jQuery script

**Why isn't my jQuery script coloring the rows as expected when certain conditions are met (I italicized the specific part of the code)?** Here is the HTML CODE for the POLL: <form id="pollForm" class="mb-4"> <d ...

Black textures with images sourced from the same domain - Cross-origin

Despite trying numerous solutions and tips to resolve the cross-origin issue, I still can't seem to fix it. There are no errors, the images are hosted on the same domain as the webgl test, but the textures appear black. Occasionally when I refresh rep ...

What is the best way to handle returning a promise when outside of the scope?

I am currently working on retrieving multiple files asynchronously from AWS S3 by utilizing Promises in my code. Although I'm using AWS S3 for fetching the files, there seems to be an issue with fulfilling the promises as it's out of scope and c ...

Using Omit<T,K> with enums does not yield the expected result in Typescript

The setup includes an enum and interface as shown below: enum MyEnum { ALL, OTHER } interface Props { sources: Omit<MyEnum, MyEnum.ALL> } const test: Props = { sources: MyEnum.ALL } // triggering a complaint intentionally I am perplexed b ...

The ng-repeat directive in my Angular app's div element is being displayed as a comment

After spending several days searching, I have yet to find a solution for my issue. It seems to be specific to the code I'm working with in Angular 1.6. I apologize for the format of my post, as this is my first time seeking help on stack overflow ...

Utilize Node.js to sort through data

One API is providing me with this type of response. I need to extract the latitude and longitude of a single entity. How can I filter this data using JavaScript (Node.js)? header { gtfs_realtime_version: "1.0" incrementality: FULL_DATASET timestamp: ...

Challenges with JavaScript arrays object

I am new to JavaScript and struggling with how to extract data from this array. Can you confirm if it is formatted correctly? Shown below is the console output of the array object: [] 0: Item {id: 0, symbol: "VBIV", boughtDate: "2018-07-22", company: "V ...

I am looking to change the state of only the element that is being moused over in a React Hooks useState function, rather than changing the

Currently, I have a component from line 61-67 that controls the state of an editIcon. The issue is that it changes the state values for all items in the column, rather than just the specific item or row it should apply to. When hovering over a span element ...

An unusual issue encountered while utilizing jQuery toggle: a straightforward illustration

Attempting to create a partial fade effect using toggle for toggling opacity values when clicking an element, but encountering an issue where nothing happens on the first click. The HTML code: <html> <head> <script type="text/javascript" s ...