工厂不在Controller内部工作

时间:2017-04-08 10:56:36

标签: angularjs

我知道这是一个非常微不足道的问题,但我无法理解这个问题。

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);

});

我检查控制台,它显示未定义。

2 个答案:

答案 0 :(得分:0)

似乎工作正常。

<强>样本

&#13;
&#13;
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;
});
&#13;
<!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="angular.js@1.2.x" 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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

问题在于我的angularjs版本和向控制器注入工厂是错误的。