I am having a service as follows
services.js
var CalculatorService = angular.module('CalculatorService', [])
CalculatorService.service('Calculator', function () {
this.square = function (a) { return a*a};
});
CalculatorService.factory('StringManipulation', function () {
var r= function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
});
Then controller as follows,
var myApp = angular.module('myApp', ['CalculatorService']);
{
myApp.controller('StringController', function ($scope, StringManipulation)
$scope.findReverse = function () {
$scope.reversename = StringManipulation.reverseString($scope.name);
}
});
and on the View using the controller as follows
<div ng-controller="StringController">
Enter Name:
<input ng-model="name">
<button class="btn btn-info" ng-click="findReverse()">Reverse
</button>
<div>{{reversename}}</div>
</div>
I am sure missing something basic. I am getting error that
Error: error:undef Undefined Value
any help ?
return
{
reverseString: function reverseString(name)
{
return r(name);
}
}
Automatic semicolon insertion is causing the problem. You must add the opening brace on the same line as the return statement. Otherwise the statement becomes return;
.
return {
reverseString: function reverseString(name)
{
return r(name);
}
}
Angular expects a return value from the factory's $get
method. Your StringManipulation
factory is returning undefined
due to automatic semicolon insertion.