如何更新控制器中的工厂阵列

时间:2016-12-23 05:59:10

标签: angularjs

我是angularjs的新手,因为我的项目developmemt我有一个所有领域都很常见的功能,所以写一个工厂并将该功能放在那个工厂里,函数调用表格控制器到这个它工作正常,但我有在工厂的一些数组,我想从控制器更新这些数组,我试过,但我无法访问控制器中的数组。请帮帮我这是我的代码。

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;
});

我的控制器代码是

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

1 个答案:

答案 0 :(得分:0)

这应该有效

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
    };
}])