Reputation: 139
Im new to angularjs. How to use a controller to access the values that are assigned inside
`
var app = angular.module('myApp', []);
app.factory('testFactory', function(){
var alpha = {};
alpha.sample=['apple','orange','grape'];
enter code here
return alpha;
}`
So here I want to access and display apple orange and grape in my view.
Upvotes: 0
Views: 1322
Reputation: 66
If your use of a factory is more complex then stated then Simon Poole's answer would be the go to but if your use is simply for the stated array then using a constant would be simpler and generally better. (Value would also work for your need see link to AngularJS Doc)
app.js
var app = angular.module('myApp', []);
app.constant('SAMPLES', ['apple', 'orange', 'grape']);
app.controller('testController', ['SAMPLES', function(SAMPLES){
var vm = this;
vm.data = SAMPLES;
}]);
html (Same as Simon Poole's answer)
<html ng-app="myApp">
<head>
...
<script src="app.js"></script>
</head>
<body ng-controller="testController as controller">
<ul>
<li ng-repeat="fruit in controller.data" ng-bind="fruit"></li>
</ul>
</body>
</html>
https://plnkr.co/Po1g0bq1MRoI6x9xAFpU
More info on providers (Service, Value, Provider, Factory, Constant) https://docs.angularjs.org/guide/providers
Upvotes: 1
Reputation: 513
You probably don't need a factory, you can define your sample data directly in the controller. Here's a quick plunker with both.
app.js
var app = angular.module('myApp', []);
app.factory('testFactory', function() {
var alpha = {};
alpha.sample = ['apple', 'orange', 'grape'];
return alpha;
});
app.controller('testController', ['testFactory', function(testFactory){
var vm = this;
vm.data = testFactory.sample;
}]);
html:
<html ng-app="myApp">
<head>
...
<script src="app.js"></script>
</head>
<body ng-controller="testController as controller">
<ul>
<li ng-repeat="fruit in controller.data" ng-bind="fruit"></li>
</ul>
</body>
</html>
https://plnkr.co/EvY6ANLlyNvgxNxx3IIg
Upvotes: 0