2016-09-14 93 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

相關問題