angularjs factory returning undefined

2019-08-10 09:17发布

问题:

I am learning the basics of AngularJS and I can´t figure out why this Factory returns an undefined value. It´ my first attempt to create and understand factories. I saw many examples on SO and on the internet but I couldn´ find the solution.

I am trying to create an array of strings (colors) on the factory and a button shown in each different view to add one string to the array. But the factory returns undefined so I can´t inject the value to the controllers.

Here is the code.

index.html

<head>
</head>

<body>
    <a href="#/">Home</a>
    <a href="#/seccion1">Seccion 1 </a>
    <div ng-view>

    </div>  
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>

    <script src="mijs.js"></script>

</body>

JS file (mijs.js) with controllers, the factory and the $routeProvider service

var app=angular.module("myMod",['ngRoute']);

app.config(
    function($routeProvider)
    {
        $routeProvider.when('/',
            {
                controller:'ctrlHome',
                controllerAs:'home',
                templateUrl:'home.html'
            }
        );

        $routeProvider.when('/seccion1',
            {
                controller:'ctrlSeccion1',
                controllerAs:'seccion1',
                templateUrl:'seccion1.html'
            }
        );
    }//end function($routeProvider)
);//end config

app.factory("factColors",function(){
    var arrayColors=['red','green','blue'];
    return arrayColors;
}); //end factory

app.controller('ctrlHome',function(factColors) 
    {
        var home=this;
        home.arrayColors=factColors.arrayColors;
    }

);//end home controller

app.controller('ctrlSeccion1',function(factColors) 
    {
        var seccion1=this;
        seccion1.arrayColors=factColors.arrayColors;
    }
);//end seccion1 controller

Here is the view home.html

<p>home view </p>
<p ng-repeat="color in home.arrayColors">{{color}}</p>

<button ng-click="home.arrayColors.push('orange')">add color</button>

And the view seccion1.html

<p>seccion 1 view </p>
<p ng-repeat="color in seccion1.arrayColors">{{color}}</p>

<button ng-click="seccion1.arrayColors.push('purple')">add color</button>

回答1:

Your factory is returning the array directly. That's fine in and of itself, but you're accessing it as though it's returning an object with an arrayColors property. So either change the factory to this:

app.factory("factColors",function(){
    return {
        arrayColors: ['red','green','blue']
    };
});

Or change the way you interact with it to this:

app.controller('ctrlSeccion1',function(factColors) {
    var seccion1=this;

    seccion1.arrayColors=factColors;
}