Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to AngularJs. I am trying to use Service.js to call Web Api. 
It is working if I directly call from controller. But when I try to segregate the code by using Service.js I am getting lost.
Any help will be appreciated.

getSubs function call is working in APIService. But not able to run the getALL().
Please help.


What I have tried:

index.cshtml
<div ng-controller="myHttpController">
<select ng-model="selectUser" ng-options="x.UserName for x in data"></select>
Error: {{error}}
</div>
********************

app.controller("myHttpController",
    function ($scope, $http) {
        $http.get('/api/Values').
            then(function (response) {
                $scope.data = response.data;
            }
            );
    });
*************************
Above part is working. 

But if I create separate Service.js file it is not working.

Index.cshtml// start
 <div ng-controller="serviceController">
            <label id="ser">{{hex}}</label>
            <p></p>
            
            Service
            <select ng-model="selectusr" ng-options="y.UserName for y in testdata"></select>
        </div>
Index.cshtml// End


Service.js //Start
app.service("APIService", function ($http) {

    this.getSubs = function (x) {
        return x.toString(16);
    }
   this.getUsers = function ($http) {
        var url = '/api/Values';
        return $http.get(url).then(function (response) {
            return response.data;
        });
    }

}); 
Service.js //END


Controller.js// Start
app.controller("serviceController", function ($scope, APIService) {
<big>I want this commented portion of code to work</big>
    //getAll(); 
    //function getAll() {
    //    APIService.getUsers()
    //        .success(function (d) {
    //            $scope.testdata = d;
    //        })
    //        .error(function (error) {
    //        console.log('Oops! Something went wrong while fetching the data.')
    //    });
    //}

    $scope.hex = APIService.getSubs(255); ----<big></big>Again It is working
});
Controller.js// End
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900