angular js中service

(1)實例

              1.在service.js中定義服務

var appServices = angular.module('appServices', ['ngResource']);

appServices.factory('reverse', [
  function(){
    return {
      myFunc:function(input){
        var res = "";
        if(input!=null){
          for(var i=input.length-1; i>=0; i--){
            res += input.charAt(i);
          }
        }
        return res;
      }
    };
  }]);
              2.在controller.js中添加服務依賴並調用
var appControllers = angular.module('appControllers', []);

appControllers.controller('IndexCtrl', ['$scope','reverse',
  function($scope,reverse) {
    $scope.data = reverse.myFunc("check");

  }]);

(2)說明

              1.定義服務格式

var appServices = angular.module('appServices', ['ngResource']);

appServices.factory('服務名稱', [
  function(){
    return {
      方法名稱:function(方法參數){
        
        return 方法返回值;
      }
    };
  }]);
              這麼看可能有些不容易看懂,看個其他例子
  var mainApp = angular.module("mainApp", []);
   mainApp.factory('MathService', function() {   
     var factory = {}; 
     factory.multiply = function(a, b) {
      return a * b 
     }
     return factory;
   }); 
         所以看出,實際上就是爲了返回一個Object實例,其中包含了多個方法,所以需要返回{}
         所以服務中的方法實際上就是Object中的一個方法而已


             2.調用服務

               必須要將service實例進行注入才能夠進行調用


(3)其他定義方式

              1.使用service方法

angular.module('myApp.services')
.service('User', function($http) { // injectables go here
  var self = this; // Save reference
  this.user = {};
  this.backendUrl = "http://localhost:3000";
  this.setName = function(newName) {
    self.user['name'] = newName;
  }
  this.setEmail = function(newEmail) {
    self.user['email'] = newEmail;
  }
  this.save = function() {
    return $http.post(self.backendUrl + '/users', {
      user: self.user
    })
  }
});
              2.使用provider方法

angular.module('myApp.services')
.provider('User', function() {
  this.backendUrl = "http://localhost:3000";
  this.setBackendUrl = function(newUrl) {
    if (url) this.backendUrl = newUrl;
  }
  this.$get = function($http) { // injectables go here
    var self = this;
    var service = {
      user: {},
      setName: function(newName) {
        service.user['name'] = newName;
      },
      setEmail: function(newEmail) {
        service.user['email'] = newEmail;
      },
      save: function() {
        return $http.post(self.backendUrl + '/users', {
          user: service.user
        })
      }
    };
    return service;
  }
});


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章