【问题标题】:Angular can not find my factoryAngular 找不到我的工厂
【发布时间】:2015-11-17 12:54:04
【问题描述】:

所以我用 angular 创建了一个小工厂来获取我的本地 json 文件,现在我想将该数据传递给我的控制器,但它找不到工厂名称并显示“未解析的变量”。

这是我的代码的 sn-p,我猜现在是相关的。

(function () {

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

    app.controller('teamController', function ($scope) {
        function init () {
            dataFactory.getTeams().success(function(data) {
                $scope.teams = data
            });
        }
        init();
        console.log($scope.teams);
    });

    // factory
    app.factory('dataFactory', function($http) {
        var team = {};

        //get local data
        team.getTeams = function() {
            return $http.get ('http://localhost:4040/');
        };
        return team;
    });

})();

我的目标只是对 $scope.teams 进行控制台记录,而不是对数据做更多的事情。

【问题讨论】:

    标签: angularjs angularjs-scope angular-controller


    【解决方案1】:

    您应该在控制器中包含“dataFactory”

    (function () {
        var app = angular.module('locatieTool', ['ngRoute']);
    
        app.controller('teamController', function ($scope, dataFactory) {
            function init () {
                dataFactory.getTeams().success(function(data) {
                    $scope.teams = data
                });
            }
            init();
            console.log($scope.teams);
        });
    
        // factory
        app.factory('dataFactory', function($http) {
            var team = {};
    
            //get local data
            team.getTeams = function() {
                return $http.get ('http://localhost:4040/');
            };
            return team;
        }); })();
    

    【讨论】:

      【解决方案2】:

      我相信您需要将您的工厂传递给控制器​​:

      app.controller('teamController', function ($scope, dataFactory) {
          function init () {
              dataFactory.getTeams().success(function(data) {
                  $scope.teams = data
              });
          }
          init();
          console.log($scope.teams);
      });
      

      【讨论】:

        猜你喜欢
        • 2020-06-12
        • 2018-11-21
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        • 2011-05-17
        • 2012-01-16
        • 2018-05-18
        • 1970-01-01
        相关资源
        最近更新 更多