问题描述
我在指令行收到 SyntaxError: Parse error
,我想在其中使用&"来自父指令的方法的单向绑定
I get SyntaxError: Parse error
at my directive line where I want to use a "&" one-way binding from a parent directive's method
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
The parent div of the ng-repeat that passes removeParentDiv
// parentDiv directive has this
scope.datasources = [];
scope.removeDatasourcePicker = function(index) {
scope.datasources.splice(index, 1); // ie take it out
};
问题似乎是 Jasmine 不喜欢 { }.删除括号会导致测试通过(由于 & 需要 {},因此会出现典型错误).
It seems the problem is that Jasmine does not like the { }. Removing the brackets results in the test going through (with typical errors since & requires {}).
推荐答案
您没有从指令中正确调用在指令范围 removeParentDiv: '&'
中传递的方法.因为你只是在做 scope.removeParentDiv({datasource_index});
这不会将 index 参数传递给方法.
You have not called method passed in directive scope removeParentDiv: '&'
correctly from directive. As you are only doing scope.removeParentDiv({datasource_index});
which would not pass index parameter to the method.
要使其正常工作,您需要进行一些更改.
For make it working, you need to do couple of changes.
指令元素方法应该是
Directive element method should be
remove-parent-div="removeParentDiv(index)"
在从指令中调用它时,通过具有 json 结构,其中 index
只是参数,datasource_index
是它的值.
and while calling it from directive, by having json structure, where index
is nothing but parameter and datasource_index
is value of it.
scope.removeParentDiv({index: datasource_index});
在调用 scope.deleteDatasource(scope.datasourceIndex);
方法后运行摘要循环,来自 click
事件,以便它更新 scope绑定.
Do run digest cycle after calling
scope.deleteDatasource(scope.datasourceIndex);
method from click
event so that it will update scope
binding.
element.bind('click', function(event) {
event.preventDefault();
scope.deleteDatasource(scope.datasourceIndex);
scope.$apply(); //to run digest cycle, to keep binding in sync
});
这篇关于单元测试 Karma Jasmine SyntaxError:解析“&"上的错误角度指令绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!