angularjs - JavaScript/Angular borrowing a function and appending parameters -
lets have service function takes static param , second custom param varies based on controller injected in. want controller/view call service function without having write custom method in controller pass custom parameter. i'm not sure if technique 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; // magic happens here // avoid writing below $scope.call = function() { examplesvc.call('param', 'firstctrl'); } }); .controller('secondctrl', function($scope, examplesvc) { $scope.call = examplesvc.call; // magic happens here // avoid writing below $scope.call = function() { examplesvc.call('param', 'secondctrl'); } });
as understand need use service in view, easiest set $scope variable service:
$scope.service=$service;
so every method service can called directly view, without creating special $scope methods.
if needed 1 method, , need change paramater then:
$scope.call = function(){ examplesvc.call.call(this,'param', 'firstctrl'); };
i created anonymous functiom calling our call ( second call builded in prototype method calling functions ) method desirable parameters.
but if service different on every usage better approach return in service constructor. can use new keyword every time , have new object of service.
//service code
return function(controller){ this.controller=controller; //here methods ... };
//controller code
$scope.service=new service("controllername");
so in approach can have different objects of service every usage, go around of singleton service tipical. try show example of approach:
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 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>
so can use our service in different way creating new objects. sending scope give possibility run configured object directly there.
Comments
Post a Comment