0

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.

1
  • You should use a controller, not a factory Commented Sep 14, 2016 at 19:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.