2017-06-09 4 views
1

私はAngularで新しく、私はAngularで構築している私のウェブサイトに構造を持ってきています。Angularのサービス

私は複数のページで使用するいくつかの機能を持っているコントローラを持っています。私はこれらの機能からより良いサービスを作ることができると聞いています。どのように私はこれを行うことができますか?

これは現在の状態のコントローラです: $ scope.city関数と$ scope.specials関数からサービスを作成するにはどうすればよいですか?

app.controller('DataCtrl', function($scope,$http){ 
    $scope.city = function(){ 
    $scope.items = []; 

    $http.get('/getdata').then(function(d){ 
     $scope.items = d.data; 
     $scope.selectedItem = $scope.items[0]; 
    },function(err){ 
     console.log(err); 
    }); 
    }; 

    /* Function for specialization data */ 
    $scope.specials = function(){ 
    $scope.special = []; 

    $http.get('/specialdata').then(function(d){ 
     $scope.special = d.data[0]; 
    },function(err){ 
     console.log(err); 
    }); 
    }; 
}); 
+0

[Angular Dependency Injection](https://angular.io/docs/ts/latest/guide/dependency-injection.html)をご覧ください。 – Oliver

答えて

1

です。

app.controller('DataCtrl', function($scope,getServiceData){ 
getServiceData.getSpecials().then(function(response){ 
     $scope.special = response.data[0]; 
    }) 
    }; 
1

serviceを定義するには、ここでは、この

app.factory('getServiceData', function($http){ 
return { 
    getSpecials: function() { 
     return $http.get("/specialdata") 
    } 
    }; 
}); 

のように試してみて、コントローラへのコントローラの注入の工場やサービスでの使用にそれをするためにあなたが怒鳴るに見るように例

//Service.js 
(function() { 
    angular.module('myApp') 
    .service('myService', service); 

    service.$inject = ['$http'] 
    function service($http) { 
     this.specialdata = function() { 
      return $http.get('/specialdata') 
     } 
    } 
})(); 

//Controller.js 
(function() { 
    angular.module('myApp') 
    .controller('DataCtrl', DataCtrl); 

    DataCtrl.$inject = ['$scope', 'myService'] 
    function DataCtrl($scope, myService) { 
     /* Function for specialization data */ 
     $scope.specials = function() { 
      $scope.special = []; 

      myService.specialdata().then(function (d) { 
       $scope.special = d.data[0]; 
      }, function (err) { 
       console.log(err); 
      }); 
     }; 
    } 
})(); 
関連する問題