我正在尝试测试指令的回调函数
要短(角1.x,业力和角度模仿):
指令指出:
指令代码:
angular.module('test', [])
.controller('alertCtrl', function($scope) {
$scope.show({
message: 'Hello'
})
})
.directive('alert', function() {
return {
controller: 'alertCtrl',
scope: {
show: '&'
}
}
})
规范:
beforeEach(function () {
$scope.show = function (message) {
alert(message)
}
})
it('must execute an expression', function(){
element = $compile(`
<alert show="show(message)"></alert>`)($scope);
$scope.$digest() // It makes no difference
scope = element.isolateScope()
scope.$digest() // It makes no difference
console.log(angular.mock.dump(scope)) // scope.show == undefined
})
编译完成后,指定属性“show”未定义。我错过了什么?
修改
完整的代码......
angular.module('test', [])
.controller('alertCtrl', function($scope) {
$scope.show({
message: 'Hello'
})
})
.directive('alert', function() {
return {
controller: 'alertCtrl',
scope: {
show: '&',
bind: '=',
string: '@'
}
}
})
describe('test', function(){
beforeEach(angular.mock.module('test'));
beforeEach(angular.mock.inject(function (_$compile_, _$rootScope_) {
$compile = _$compile_;
$scope = _$rootScope_.$new();
}))
beforeEach(function () {
$scope.show = function (message) {
alert(message)
}
$scope.bind = {data: 123}
})
it('must execute an expression', function(){
element = $compile(`
<alert show="show(message)"
bind="bind"
string="'World'"
></alert>`)($scope);
$scope.$digest() // It makes no difference
scope = element.isolateScope()
scope.$digest() // It makes no difference
console.log(angular.mock.dump(scope)) // scope.show == undefined
})
})
业力的输出...... 警告:'你好' 日志:'范围(3):{ show:undefined bind:{“data”:123} 字符串:“'世界'” }” Chrome 59.0.3071(Linux 0.0.0):执行1次成功1次(0.01秒/ 0.036秒)
答案 0 :(得分:0)
看起来你在错误的共享范围var中声明了show函数。你是否在你的declare语句下声明了范围var,并在$ beforeScope的前面使用它来启动它。$ new()然后将你的函数添加到它然后将它传递给你的指令instanciation?