2016-12-23 3 views
1

Ich bin neu zu angularjs, für meine Projektentwicklung Ich habe eine Funktion, die allen Feldern gemeinsam ist, so schreiben Sie eine Fabrik und platzieren Sie diese Funktion in dieser Fabrik, Funktion ruft Form Controller bis zu diesem Es funktioniert gut, aber ich habe einige Arrays in der Fabrik, ich möchte diese Arrays vom Controller aktualisieren, ich habe versucht, aber ich bin nicht in der Lage, auf das Array im Controller zugreifen. Bitte hilf mir das ist mein Code.Wie update Factory-Array in Controller

regapp.factory('commonFactory',function(){ 
var suggestion=[]; 
var obj={}; 
obj.suggestion['years1']=obj.suggestion['years2']=["2016", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997", "1996", "1995", "1994", "1993", "1992", "1991", "1990", "1989", "1988", "1987", "1986", "1985", "1984", "1983", "1982", "1981", "1980", "1979", "1978", "1977", "1976", "1975", "1974", "1973", "1972", "1971", "1970"]; 
return obj; 
}); 

und mein Controller-Code

regapp.controller('mycontroller', function($scope, $http, $state,commonFactory){ 
console.log(commonFactory.suggestion['wyear'].slice(0,5)); 
}): 
+0

So etwas wie 'obj.suggestion [ 'wYear'] ist Arbeit ist undefined'. Überprüfen Sie erneut dafür –

Antwort

0

sollte

regapp.controller('mycontroller', function($scope, $http, $state, commonFactory) { 
    // get 
    var suggestions = commonFactory.getSuggestions(); 
    // add new 
    commonFactory.setSuggestions('your suggestion', 'wyear'); 

}): 


regapp.factory('commonFactory', [function() { 
    var suggestion = []; 
    var obj = {}; 

    obj.suggestion['years1'] = obj.suggestion['years2'] = ["2016", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997", "1996", "1995", "1994", "1993", "1992", "1991", "1990", "1989", "1988", "1987", "1986", "1985", "1984", "1983", "1982", "1981", "1980", "1979", "1978", "1977", "1976", "1975", "1974", "1973", "1972", "1971", "1970"] 

    function getSuggestions() { 
     return obj; 
    } 

    function setSuggestions(suggestion, arrayToPush) { 
     if (obj.suggestion[arrayToPush.toString()]) { 
      obj.suggestion[arrayToPush.toString()].push(suggestion) 
     } else { 
      obj.suggestion[arrayToPush.toString()] = []; 
      obj.suggestion[arrayToPush.toString()].push(suggestion) 
     } 

    } 
    return { 
     getSuggestions: getSuggestions, 
     setSuggestions: setSuggestions 
    }; 
}]) 
Verwandte Themen