2016-12-01 102 views
-1

我的控制器:如何創建自定義服務?

app.controller('myCtrl', function($scope, $http, $timeout) { 
$scope.getData = function() { 
    $http.get("../send") 
     .then(function(response) { 
       $scope.text = response.data; 
       $scope.params = $scope.text.split(' '); 
       $scope.timeFunc(); 
      }, 
      function(response) { 
       $scope.timeFunc(); 
      }); 
}; 
$scope.timeFunc = function() { 
    $timeout(function() { 
     $scope.getData(); 
    }, 1000); 
}; 

$scope.getData(); 

}); 

如何可以做到這一點,而不是在控制器,並且它是一個單獨的服務? 的問題是,可變params應每秒更新一次

回答

0

app.controller('myCtrl', function ($scope, $http, $timeout, servicenName) { 
 
\t $scope.getData = function() { 
 
\t \t servicenName.getData().then(function (response) { 
 
\t \t \t $scope.text = response.data; 
 
\t \t \t $scope.params = $scope.text.split(' '); 
 
\t \t \t $scope.timeFunc(); 
 
\t \t }, 
 
\t \t \t function (response) { 
 
\t \t \t $scope.timeFunc(); 
 
\t \t }); 
 
\t }; 
 

 
\t $scope.timeFunc = function() { 
 
\t \t $timeout(function() { 
 
\t \t \t $scope.getData(); 
 
\t \t }, 1000); 
 
\t }; 
 
\t $scope.getData(); 
 
}); 
 
app.service('servicenName', function ($http) { 
 
\t this.getData = function() { 
 
\t \t return $http.get("../send"); 
 
\t }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>