javascript-单元测试Karma Jasmine SyntaxError:“&”角度指令绑定上的解析错误
作者:互联网
我在要使用“&”的指令行中收到SyntaxError:解析错误.与父指令的方法进行单向绑定
myApp.directive('datasourceDeleteBtn', [function() {
return {
restrict: 'E',
replace: true,
template: '<a href="#">✕</a>',
scope: {
datasourceIndex: '@',
removeParentDiv: '&'
},
link: link
};
function link(scope, element, attr) {
element.bind('click', function(event) {
event.preventDefault();
scope.deleteDatasource(scope.datasourceIndex);
});
// Notify parent directive
scope.deleteDatasource = function(datasource_index) {
// conditional stuff that happens not included
// {} required for passing values to "&" parent scope method
scope.removeParentDiv({datasource_index});
};
}
}]);
的HTML
<parent-div ng-repeat> // this is just a mockup not literal
<datasource-delete-btn datasource-index="{{$index}}" remove-parent-div="removeParentDiv()"></datasource-delete-btn>
</parent-div>
传递removeParentDiv的ng-repeat的父div
// parentDiv directive has this
scope.datasources = [];
scope.removeDatasourcePicker = function(index) {
scope.datasources.splice(index, 1); // ie take it out
};
看来问题在于Jasmine不喜欢{}.卸下括号会导致测试继续进行(由于&要求{},因此会出现典型错误).
解决方法:
You are getting error because you are passing json in wrong format in
method
您尚未调用在指令范围removeParentDiv中传递的方法:’&’正确地从指令.因为您只在做scope.removeParentDiv({datasource_index});不会将索引参数传递给该方法.
为了使其正常工作,您需要进行一些更改.
>指令元素方法应为
remove-parent-div="removeParentDiv(index)"
>并在指令中通过json结构调用它,其中index只是参数,datasource_index是它的值.
scope.removeParentDiv({index: datasource_index});
>在调用scope.deleteDatasource(scope.datasourceIndex);之后运行摘要循环. click事件中的方法,以便它将更新作用域绑定.
element.bind('click', function(event) {
event.preventDefault();
scope.deleteDatasource(scope.datasourceIndex);
scope.$apply(); //to run digest cycle, to keep binding in sync
});
标签:angularjs,karma-jasmine,angularjs-directive,javascript 来源: https://codeday.me/bug/20191119/2032922.html