【问题标题】:Can't get factory or service to be recognized in controller with angluarjs using angular-seed无法使用 angular-seed 使用 angularjs 在控制器中识别工厂或服务
【发布时间】:2013-01-03 21:23:33
【问题描述】:

调用工厂时,我不断收到“未定义不是函数”。我正在使用 angular-seed 作为我的设置框架。由于某种原因,它无法将“GetFormVals”识别为有效的工厂。

在 app.js 中:

var app = angular.module('myApp', ['myApp.filters',
'myApp.services', 'myApp.directives'], function($routeProvider, $locationProvider) {
    //route declarations
    $routeProvider.when('/fsr', {
        templateUrl: 'partials/fsr.html',
        controller: ctrlFSR
    });

    $locationProvider.html5Mode(true);
});

在 controllers.js 中:

function ctrlFSR($scope, $http, $location, GetFormVals) {
    $scope.test = GetFormVals();
}
ctrlFSR.$inject = ['$scope','$location'];

在 services.js 中:

'use strict';

/* Services */

angular.module('myApp.services', []).
    factory('GetFormVals', function(){
    return "test";
});

我必须遗漏一些简单的东西。

jsfiddle:http://jsfiddle.net/wUjw5/11/

【问题讨论】:

    标签: service controller angularjs factory


    【解决方案1】:

    您需要列出要注入控制器的所有依赖项:

    function ctrlFSR($scope, $http, $location, GetFormVals) {
        $scope.test = GetFormVals();
    }
    ctrlFSR.$inject = ['$scope', '$http', '$location', 'GetFormVals'];
    

    【讨论】:

    【解决方案2】:

    把你的服务改成这个

    'use strict';
    
    /* Services */
    
    angular.module('myApp.services', []).
        factory('GetFormVals', function(){
                return {
                    exampleValue: "test5"
                }
        });
    

    然后在您的控制器中将其更新为:

    function ctrlFSR($scope, $http, $location, GetFormVals) {
        $scope.test = GetFormVals.exampleValue;
    }
    ctrlFSR.$inject = ['$scope','$location'];
    

    我认为您将 GetFormVals 调用为一个函数时产生了混淆,而实际上它是一个服务。

    jsfiddlehttp://jsfiddle.net/rtCP3/49/


    你的 js fiddle 修改了 http://jsfiddle.net/wUjw5/12/

    不要使用 ctrlFSR.$inject = ['$scope','$location']; 注入。你已经是了。

    【讨论】:

    • 感谢您的快速响应。我试过了,现在我收到“无法读取未定义的属性'exampleValue'”错误。
    • 哎呀,你说得对,我把它与实际的 .service 方法混淆了。我发布了一个 jsfiddle 并修改了我的答案。
    • 还是不行。再次感谢您的帮助。我用我的代码创建了一个 jsfiddle:jsfiddle.net/wUjw5/11 我还根据 pkozlowski.opensource reco 注入了工厂,但这也没有帮助。
    • 你注入了两次东西,我觉得这就是导致问题的原因。
    • Matt,你的第一篇文章帮助解决了问题,我需要注入来进行缩小。谢谢大家的帮助!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多