我无法获得指令的范围(另一种选择是获得范围但我的功能不存在)。我在Karma上使用Jasmine。

我的指令:

angular.module('taskApp').directive('nkAlertDir', ['$http', function ($http) {
    return {
        template: "<span>{{msg}}</span>",
        replace: true,
        link: function (scope, elem, attrs) {
            scope.values = {
                canvas: canvasSize,
                radius: size,
                center: canvasSize / 2
            };

            $http.get('someUrl')
                .suncces(function (data) {
                    scope.msg = data;
                })
                .error(function (err) {
                    //there is always be error because this url does nor exist
                    //but this is not the point in this exercise
                });

            scope.returnNumbers = function () {
                return [2, 2];
            }
        }
    }
}]);


我的测试:

describe('Unit: Directives', function () {

    var element;
    var scope;

    beforeEach(module('taskApp'));

    beforeEach(inject(function ($compile, $rootScope) {

        scope = $rootScope;
        element = angular.element('<div nk-alert-dir></div>');

        scope.size = 100;
        $compile(element)(scope);
        scope.$digest();
    }));

    it('should bind an alert message of "task added!"', function () {

        var dirScope = element.isolateScope();
        console.log(dirScope);
    });
});


我总是以某种方式获取dirScope是未定义的
我已经试过了:


替换了digest()中的$apply()
替换了$rootScope中的$rootScope.$new()

最佳答案

您的指令中没有孤立的作用域,因此element.isolateScope()将返回undefined。

尝试仅访问范围:element.scope()

如果要在指令上使用隔离范围,则必须将指令定义对象的scope属性设置为JS对象,然后在其中添加属性。然后,您将可以使用element.isolateScope来访问隔离范围。

return {
        template: "<span>{{msg}}</span>",
        replace: true,
        scope : {},   // Any properties you want to pass in to the directive on scope would get defined here
        link: function (scope, elem, attrs) {
            scope.values = {
                canvas: canvasSize,
                radius: size,
                center: canvasSize / 2
            };

            $http.get('someUrl')
                .suncces(function (data) {
                    scope.msg = data;
                })
                .error(function (err) {
                    //there is always be error because this url does nor exist
                    //but this is not the point in this exercise
                });

            scope.returnNumbers = function () {
                return [2, 2];
            }
        }
    }

关于javascript - 如何在Jasmine Test中访问指令的范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31921392/

10-09 15:02
查看更多