2016-05-04 28 views
0

我想添加函數到一個JS對象將被用作一個單身服務。使用Javascript對象角服務

angular 
     .module('app.steps') 
     .factory('createStepsService', createStepsService); 

    createStepsService.$inject = []; 

    /* @ngInject */ 
    function createStepsService() { 
     var steps; 

     var service = { 
      newSteps: function (current_step, total_steps) { 
       if (!steps) {     
        return new Steps(current_step, total_steps); 
       } 
      }    
     }; 
     return service; 

     function Steps(current_step, total_steps) { 
      this.c_step = current_step; 
      this.t_step = total_steps;    
     } 

     Steps.prototype = { 
      addSteps: function (num) { 
       this.c_step += num; 
      }, 
      setLastStep: function() { 
       this.lastStep = this.c_step = this.t_step; 
      } 
     };   
    } 

當我運行從控制器這一行,我不能夠訪問 addSteps/setLastStep方法。

vm.createStepsService = createStepsService.newSteps(1, 3); 

爲什麼我沒有看到這些方法?他們是否創造了?

謝謝。

回答

1

您的steps.prototype代碼永遠不會運行。

這是因爲它出現在return之後。

更改代碼的這個順序:

/* @ngInject */ 
function createStepsService() { 
    var steps; 

    function Steps(current_step, total_steps) { 
     this.c_step = current_step; 
     this.t_step = total_steps;    
    } 

    Steps.prototype = { 
     addSteps: function (num) { 
      this.c_step += num; 
     }, 
     setLastStep: function() { 
      this.lastStep = this.c_step = this.t_step; 
     } 
    }; 

    var service = { 
     newSteps: function (current_step, total_steps) { 
      if (!steps) {     
       return new Steps(current_step, total_steps); 
      } 
     }    
    };  

    return service; 
} 

,你可以有一個函數聲明前一回是因爲JavaScript variable and function hoisting原因。

+0

工程很棒。謝謝! – badigard

+0

@badigard很高興幫助!瞭解變量提升和功能提升工作如何值得了解。這將幫助您編寫更好的代碼。 –

1

你的問題是你在return聲明後創建Steps.prototype,所以它永遠不會被讀取。

+0

沒有錯誤。只是回報是錯位的。 – badigard

+0

確實@badigard – floribon

0

在AngularJS中,服務是單例對象,每個應用程序僅實例化一個對象。

而factory()方法是創建和配置服務的快速方法。 它提供了函數的返回值,即需要創建一個對象,向它添加屬性,然後它將返回相同的對象。

對於前:

angular 
.module('myApp',[]) 
.factory("createStepService", function(){ 
    var stepServiceObj = {}; 
    var c_step = 0; 
    var t_steps = 0; 
    var last_step = 0; 

    stepServiceObj.setCurrentStep = function(current_step){ 
     c_step = current_step; 
     console.log('c_step1: ',c_step); 
    }; 
    stepServiceObj.getCurrentStep = function(){ 
     return c_step; 
    }; 

    stepServiceObj.setTotalStep = function(total_steps){ 
     t_steps = total_steps; 
    }; 
    stepServiceObj.getTotalStep = function(){ 
     return t_steps; 
    }; 

    stepServiceObj.setLastStep = function(){ 
     last_step = c_step = t_step; 
    }; 
    stepServiceObj.getLastStep = function(){ 
     return last_step; 
    }; 

    stepServiceObj.addSteps = function(num){ 
     return c_step += num; 
    }; 

    return stepServiceObj; 
});