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>