【问题标题】:function foo(param) { alert("foo called"); } and $scope.foo = function(param){alert("foo");};函数 foo(param) { alert("foo 调用"); } 和 $scope.foo = function(param){alert("foo");};
【发布时间】:2014-11-09 19:00:13
【问题描述】:

我想我在使用 AngularJS 时遇到了类似的问题,就像许多其他人一样。 我正在修复以前的错误消息(我无法调用 测试描述块中的控制器功能)并获得了新的 错误。

错误:[ng:areq] 参数 'fooController' 不是函数,未定义

我已经阅读了其他帖子,但仍然无法更正。

所以我的控制器就像..

'use strict';

var app = angular.module('MyApp', ['MyAppControllers']);
var appControllers = angular.module('MyAppControllers', []);

appControllers.controller('fooController', ['$scope', function ($scope) {
function foo(param) {
    alert("foo called");
}
}]);

我的控制器规格是..

'use strict';

describe('fooController', function () {
    var $scope, $controller;

    beforeEach(inject(function ($rootScope, $controller) {
        $scope = $rootScope.$new();
        ctrl = $controller('fooController', { $scope: $scope });
    }));

    it("should write foo called", function () {
        $scope.foo();
   });
});

为什么老是说 fooController 不是函数??

谢谢大家。

旧帖已编辑。请您阅读底部的帖子(我的新问题?:))

【问题讨论】:

    标签: javascript angularjs karma-jasmine use-strict unit-testing


    【解决方案1】:

    更换控制器

    appControllers.controller('fooController', ['$scope', function ($scope) {
    
    //add your function within scope
    $scope.foo = function(){
     alert("foo called");
    }
    }]);
    

    【讨论】:

    • 因为'使用严格';我不能。还有其他方法吗?
    • 我试图杀死'use strict';并遵循建议。仍然出现同样的错误。
    【解决方案2】:

    好吧。我傻了。描述后我没放。

    所以我现在解决了这个问题:

    'use strict';
    
    describe('fooController', function () {
        **beforeEach(module('MyApp'))**;
        var $scope, ctrl;
    
        beforeEach(inject(function ($rootScope, $controller) {
            $scope = $rootScope.$new();
            ctrl = $controller('fooController', { $scope: $scope });
        }));
    
        it("should write foo called", function () {
            $scope.foo("aa");
        });
    });
    

    和控制器..

    'use strict';
    
    var app = angular.module('MyApp', ['MyAppControllers']);
    
    var appControllers = angular.module('MyAppControllers', []);
    
    appControllers.controller('fooController', ['$scope', function ($scope) {
        function foo(param) {
            alert("foo called");
        }
    }]);
    

    如果可以的话,我现在想问一下我原来的问题。

    问题是从控制器规范的测试块中看不到函数 foo TypeError: undefined is not a function

    我看到一个帖子说函数是私有的,应该把函数变成l

    $scope.foo = function(param){alert("foo");};
    

    但是 'use strict' 禁止像上面这样的转动功能。

    我想知道其他人是如何解决这个问题的?

    再次感谢您。

    【讨论】:

    • 好吧,你可以使用 '$scope.foo = function(param){alert("foo");};' 'use strict' 下的这一行。我仍然不知道之前是什么阻止了这种情况。
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    • 2015-05-06
    • 2010-12-12
    • 1970-01-01
    • 2013-01-30
    相关资源
    最近更新 更多