2017-04-08 112 views
0

我知道這是非常微不足道的問題,但我無法理解問題。工廠不在控制器內

myApp.factory("States", ['runajax', function(runajax) { 
    var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Dakota", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]; 

    return states; 

}]); 

myApp.controller("TypeaheadCtrl", function($scope, States) { 

    $scope.selected = undefined; 

    $scope.states = States; 

console.log($scope.states); 

}); 

我檢查控制檯,它顯示未定義。

+0

可能與「runajax」是什麼有關,它與所顯示的不同 – charlietfl

+0

即使沒有runjax服務,它也不起作用。我一直未定義 –

+0

顯示的代碼的工作原理如下所示。按照[mcve]創建演示文稿,再現問題 – charlietfl

回答

0

它似乎工作正常。

DEMO

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

 
app.factory('States', function(){ 
 
    var states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Dakota", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"]; 
 
    return states; 
 
}) 
 

 

 
app.controller("TypeaheadCtrl", function($scope, States) { 
 
    $scope.selected = undefined; 
 
    $scope.states = States; 
 
    console.log($scope.states); 
 

 
}); 
 
app.controller('SecondCtrl', function($scope, States){ 
 
    $scope.data_list_2 = States.data; 
 
});
<!DOCTYPE html> 
 
<html ng-app="plunker"> 
 

 
    <head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    <script>document.write('<base href="' + document.location + '" />');</script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://code.angularjs.org/1.2.25/angular.js" data-semver="1.2.25"></script> 
 
    <script src="app.js"></script> 
 
    </head> 
 

 
    <body> 
 
     <div ng-controller="TypeaheadCtrl"> 
 
      <p>Main Controller {{states}}</p> 
 
     </div> 
 
     
 
     <div ng-controller="SecondCtrl"> 
 
      <p>Second {{states}}</p> 
 
     </div> 
 
    </body> 
 

 
</html>

0

的問題是與我angularjs版本和工廠的注射控制器是錯誤的。

+0

請詳細說明:你的angularjs版本有什麼問題?工廠注入有什麼問題?預計答案將完全回答這個問題。見[回答]。 –