我正在尝试测试一个绑定到指令的控制器。
app.module('App')
.directive('myDirective', function() {
return {
templateUrl: '../my-directive.html',
scope: true,
bindToController: {
model: '='
},
controller: 'DirectiveCtrl as DirectiveCtrl'
};
})
.controller('DirectiveCtrl', function() {
var DirectiveCtrl = this,
model = DirectiveCtrl.model;
DirectiveCtrl.resetValue = function() {
DirectiveCtrl.model = model;
};
});
在测试中,
describe('DirectiveCtrl', function() {
var DirectiveCtrl,
model = {
id: 'id',
name: 'name'
};
beforeEach(module('App'));
beforeEach(inject(function($controller) {
DirectiveCtrl = $controller('DirectiveCtrl');
// code to initialize controller with model value;
}));
it('resets the default value', function() {
DirectiveCtrl.resetValue();
expect(DirectiveCtrl.model).toEqual(model);
});
});
我想以与指令编译期间有界控制器的行为方式类似的方式初始化控制器。我怎么能这样做?
答案 0 :(得分:1)
我终于找到了角$controller decorator的解决方案。第二个参数采用带有绑定值的对象。
所以测试将是,
describe('DirectiveCtrl', function() {
var DirectiveCtrl,
model = {
id: 'id',
name: 'name'
};
beforeEach(module('App'));
beforeEach(inject(function($controller) {
DirectiveCtrl = $controller('DirectiveCtrl', {
model: model
});
}));
it('resets the default value', function() {
DirectiveCtrl.resetValue();
expect(DirectiveCtrl.model).toEqual(model);
});
});