2016-08-02 134 views
0

我可以返回一個對象,但不返回對象屬性。爲什麼?我嘗試了很多東西,但似乎沒有任何工作。很抱歉,但我在角不返回對象屬性的角廠

app.factory('myData', function() { 

    var data = { 
    product: '' 
    }; 


    function addItem(value) { 
    data.product = value; 
    } 

    function getList() { 
    return data.product; 
    } 

    return { 
    addItem: addItem, 
    getList: getList 
    }; 

}); 

與控制器功能

function controllerA(myData){ 

    var scope = this; 
    scope.total = 0; 

    scope.addMore = function(){ 
    scope.total++; 
    myData.addItem(scope.total); 
    } 

} 

function controllerB(myData){ 

    var scope = this; 
    scope.total = 0; 
    scope.total = myData.getList(); 

} 
+0

這看起來沒問題。當你調用getList()時,你會得到'undefined'或''''? –

+0

你可以做一個這樣的plunkr嗎?正如muli所說,這看起來應該返回對象屬性好嗎 –

+0

那麼,什麼是「不起作用」的代碼,你期望它做什麼,它做什麼呢? –

回答

0

更新新的可以讀好文章:

aticle

demo.factory(
      "Friend", 
      function(trim) { 
       // Define the constructor function. 
       function Friend(firstName, lastName) { 
        this.firstName = trim(firstName || ""); 
        this.lastName = trim(lastName || ""); 
       } 
       // Define the "instance" methods using the prototype 
       // and standard prototypal inheritance. 
       Friend.prototype = { 
        getFirstName: function() { 
         return(this.firstName); 
        }, 
        getFullName: function() { 
         return(this.firstName + " " + this.lastName); 
        } 
       }; 
       // Define the "class"/"static" methods. These are 
       // utility methods on the class itself; they do not 
       // have access to the "this" reference. 
       Friend.fromFullName = function(fullName) { 
        var parts = trim(fullName || "").split(/\s+/gi); 
        return(
         new Friend(
          parts[ 0 ], 
          parts.splice(0, 1) && parts.join(" ") 
         ) 
        ); 
       }; 
       // Return constructor - this is what defines the actual 
       // injectable in the DI framework. 
       return(Friend); 
      } 
     ); 
1

在控制器B的總在控制器被實例化時被初始化。

當調用addMore()時,控制器A中的總數被修改。所以,如果你控制器B實例化addMore(),控制器B將一直引用原始值加時賽總:空字符串:

t0: controller A is instantiated 
t1: controller B is instantiated. B.total is initialized with the result of myData.getList(), which is the empty string: 

    data.product -------\ 
         | 
         V 
    B.total -------> empty string 


t2: a.addMore() is called. That modifies the service's total, but not the variable in B 

    data.product ---> 1 


    B.total -------> empty string 

如果參照對象本身的控制器,你不有這個問題,因爲B有一個參考數據,而data.product被A修改。

+0

謝謝。我認爲這是問題。但是我能做些什麼呢? –

+0

@cdz從您的服務中返回對象。從服務中返回原語幾乎總是會導致這種情況,即控制器中的值永遠不會更新。 – Lex