1

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>

1 Answer 1

1

I tried out myself, the solution is: service[param]($scope.v); param is the function name to be invoked.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.