[英]Angular, adding scope is breaking my directive
I am having trouble getting this directive to work properly, It was working fine until I tried adding a scope to link a function. 我在使该指令正常工作方面遇到麻烦,在尝试添加作用域以链接功能之前,它一直工作良好。 Here's what I have so far 这是我到目前为止的
The directive (in requirejs format hence the module/component name stuff) : 指令(使用requirejs格式,因此使用模块/组件名称):
angular.module(metadata.moduleName, [
filterFieldControl.moduleName
]).directive(metadata.componentName,
function(scope) {
return {
controller: filterFieldControl.componentName,
restrict: 'C',
replace: true,
scope: {
filterFn: '='
},
template: builderResultFiltersHTML
};
}
);
The controller 控制器
angular.module(metadata.moduleName, []).controller(metadata.componentName, [
'$scope',
function($scope) {
$scope.filterChange = function() {
$scope.filterFn();
};
}
]);
The template: 模板:
<div>
<ul>{{filter.name}}
<li ng-repeat="value in filter.values">
<input type="checkbox" ng-model="filterObject[filter.name][value]" ng-change="filterChange()">{{value}}
</li>
</ul>
Where it is being used (and maybe some of the issue is it's being repeated?) 在哪里使用它(也许是重复出现的一些问题?)
<div ng-repeat="result in searchResults.results" class="builder-search-result" filter-fn="filterClicked" ></div>
So if I take out the scope from the directive it works fine. 因此,如果我从指令中删除范围,它会很好地工作。 If i add it in, there are no errors in console but nohting shows up. 如果我添加它,控制台中没有错误,但没有出现提示。
If I remove this, it works : 如果我删除它,它可以工作:
scope: {
filterFn: '='
},
Can't seem to figure out why. 似乎无法弄清楚原因。 Could use some ideas. 可以使用一些想法。
Edit: added fiddle here https://jsfiddle.net/vt1uasw7/31/ - you will notice if you remove the scope part of the directive, everything shows up fine. 编辑:在这里添加了小提琴https://jsfiddle.net/vt1uasw7/31/-您将注意到,如果删除指令的作用域部分,一切都会很好。
When you do scope: { ... }
in a directive, you're telling Angular to create an isolate scope , which is a scope that doesn't prototypally inherit from any other scope. 当您在指令中执行scope: { ... }
时,您是在告诉Angular创建一个单独的范围 ,该范围不是原型上不会从任何其他范围继承的。
Now, take a look at your directive's template: 现在,看一下指令的模板:
<div>in
<ul>{{filter.name}}
<li ng-repeat="value in filter.values">
<input type="checkbox" ng-change="filterChange()">{{value}}
</li>
</ul>
</div>
Both filter
and filterChange()
are defined in the controller's scope, and your directive can't access them because it has its own private scope. filter
和filterChange()
都在控制器的作用域中定义,您的指令无法访问它们,因为它具有自己的私有作用域。
You can fix your code by doing one of two things: 您可以通过执行以下两项操作之一来修复代码:
$parent.filter
and $parent.filterChange()
; 使用$parent.filter
和$parent.filterChange()
; Add filter
and filterChange
to the directive's isolate scope: 将filter
和filterChange
添加到指令的隔离范围:
scope: { filter: '=', filterChange: '&' }
I suggest #2. 我建议#2。 Here 's your updated fiddle. 这是您更新的小提琴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.