jazzoria jazzoria - 2 months ago 10
AngularJS Question

angularjs using factory and controller

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.

Answer

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