我无法获得我的指令的范围(另一种选择是我获得了范围但我的功能不在那里)。我在 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 is undefined 我试过这个:
- 替换了
$apply()
中的digest()
- 替换了
$rootScope.$new()
中的$rootScope
最佳答案
您的指令中没有隔离作用域,因此 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/