2016-09-14 97 views
0

Im新的angularjs。如何使用一个控制器来访问内部angularjs使用工厂和控制器

`

var app = angular.module('myApp', []); 

app.factory('testFactory', function(){ 

var alpha = {}; 

alpha.sample=['apple','orange','grape']; 

    enter code here 

return alpha; 
    }` 

所以在这里我想访问和显示苹果橘子和葡萄中我认为被分配的值。

+0

您应该使用控制器,而不是工厂 – holtc

回答

0

您可能不需要需要一个工厂,您可以直接在控制器中定义您的样品数据。 这里有一个快速与两者。

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

1

如果你的工厂的使用是比较复杂的,然后说那么西蒙·普尔的答案将是去,但如果你的使用只是为了所述的数组,然后使用一个常数w应该更简单,通常更好。 (价值也将工作您的需求,请参阅链接AngularJS文件)

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(同西蒙·普尔的答案)

<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

更多信息提供者(服务,价值,提供者,工厂,常量) https://docs.angularjs.org/guide/providers

相关问题