I want to invoke a function within a service based on the function name.
For example, passing a string as the function name and invoke it dynamically.
Can this be implemented using angular way?
The code in plunker is : http://plnkr.co/edit/A9RjFqcuc1FfuqmC4o02?p=preview
Main code is also listed below for your quick glance:
var app = angular.module('app', []);
app.service("testService", [ function() {
this.test = function(value){
alert(value);
};
}])
app.controller('testController', ['$scope', '$injector', '$parse', function($scope, $injector, $parse) {
$scope.v = '123';
$scope.click = function(param) {
var service = $injector.get('testService');
// service.test($scope.v);
var expressionHandler = $parse('service.' + param + '($scope.v)');
// expressionHandler($scope);
// $scope.$apply(function() {expressionHandler($scope, $scope.users);});
// $scope.$eval('service.test', {'value': $scope.value})
};
}]);
<!doctype html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="testController">
<button type="button" ng-click="click('test')">click</button>
</div>
</body>
</html>