a__pal Ответов: 0

Я не могу разделить контроллер и сервисный код в angularjs.


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.


Что я уже пробовал:

индекс.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

0 Ответов