我正在创建一个AngularJS组件,该组件(WILL)提供了一个复选框列表指令,其中包含过滤,排序,切换选项,滚动等...一旦完成。它应该帮助人们处理长时间的复选框列表。
我正在尝试通过标签或ID功能测试订单,但是即使在$ digest或$ apply通话后,模板也不会反映模型更改。我试图解决但无法解决。
这是指示定义:
angular.module('angularjsSmartcheckboxApp')
.directive('smartCheckbox', [function () {
return {
templateUrl: 'views/smartcheckbox.html',
restrict: 'E',
replace: true,
scope: {model: '='},
controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {
// TODO
}]
};
}]);
用法:
<smart-checkbox model="smartList" />
smartList是:
$scope.smartList = [
{id: '001', label: 'First item'},
{id: '002', label: 'Second item'},
{id: 'Z01', label: 'Another item'}
];
这是模板:
...
<div class="input-group ordercontrols">
Order options:
<label class="radio-inline">
<input type="radio" value="label" ng-model="orderby"> Label
</label>
<label class="radio-inline">
<input type="radio" value="id" ng-model="orderby"> Id
</label>
<label>
<input type="checkbox" ng-model="reverse" />
Reverse
</label>
</div>
<div>
<div class="checkbox widgetcontrols" ng-repeat="elem in model | filter:{$:filter} | orderBy: orderby:reverse">
<label>
<input class="smart" type="checkbox" ng-model="elem.value" value="{{elem.value || false}}" />
<span class="itemid">[{{elem.id}}]</span> {{elem.label}}
</label>
</div>
</div>
在这里您可以找到失败的测试"标签顺序(反向)":
describe('Directive: smartCheckbox', function () {
// load the directive's module
beforeEach(module('angularjsSmartcheckboxApp', 'views/smartcheckbox.html'));
var element,
$rootScope,
$compile,
scope;
beforeEach(inject(function (_$rootScope_, _$compile_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
$compile = _$compile_;
$rootScope.model = [
{id: '001', label:'First item'},
{id: '002', label:'Second item'}
];
element = $compile(angular.element('<smart-checkbox model="model"></smart-checkbox>'))(scope);
$rootScope.$apply();
}));
it('Labels order (reverse)', function () {
scope.reverse = true;
scope.orderby = 'label';
scope.$apply();
expect(element.children().eq(3).find('label').eq(0).find('span').text()).toBe('[002]');
});
});
存储库链接:https://github.com/davidemoro/angularjs-smartcheckbox
ps:如果您打开浏览器,则重新排序工作正常,因此我想测试方法中有问题。
有什么问题?预先感谢
我如何解决它:
- element = $compile(angular.element('<smart-checkbox model="model"></smart-checkbox>'))(scope);
+ $element = angular.element('<smart-checkbox model="model"></smart-checkbox>');
+ element = $compile($element)(scope);
...
it('Labels order (reverse)', function () {
- scope.reverse = true;
- scope.orderby = 'label';
- scope.$apply();
+ $element.isolateScope().reverse = true;
+ $element.isolateScope().orderby = 'label';
+ $element.isolateScope().$apply();
- expect(element.children().eq(3).find('label').eq(0).find('span').text()).toBe('[002]');
+ expect($element.children().eq(3).find('label').eq(0).find('span').text()).toBe('[002]');
});
由于指令使用孤立的范围,因此我需要使用.isolateScope方法。希望它可以帮助其他人:)
更新:我已经根据此答案写了一篇博客文章。请参阅http://davidemoro.blogspot.com/2014/02/testing-angularjs-directives-with_13.html