我有一组客户端,显示在表单上,它们必须具有单独的范围(每个客户端):
当然,我希望创建一个具有隔离范围的新指令,不会允许使用如下自定义指令将元素绑定(bind)到 oustide $scope
:
<fieldset client="156510">
<legend>Client 156510</legend>
<!-- Form elements -->
</section>
</fieldset>
同样:
angular.module("plunker", [])
.controller("ClientCtrl", function($scope) {})
.directive("client", function() {
return {
restrict: "A",
scope: {
name: "@name",
client: "=client"
}
};
});
鉴于 ng-repeat
不是一个选项,我如何使用指令隔离任何包含的 HTML 的范围? Angular 文档 seem to suggest this is possible ,但我的实现似乎没有按预期工作。
提前致谢。
最佳答案
在没有 template/templateUrl 的独立作用域的元素上的任何指令实际上都不会获得新的作用域。
这是证据 http://plnkr.co/edit/jXwrtG?p=preview
.directive("client", function() {
return {
restrict: "A",
template: ' ',//notice extra spaces
replace: true,//notice this
scope: {
name: "@name",
client: "=client"
}
};
});
scope=true 也可以解决您的问题。
http://plnkr.co/edit/JdiCVV?p=preview
.directive("client", function() {
return {
restrict: "A",
scope: true
};
});
也正如@imscrb所指出的 transclude = true 也可以,但您必须将 ng-transclude 添加到元素
<fieldset client="156510" ng-transclude>
http://plnkr.co/edit/b0hX5h?p=preview
.directive("client", function() {
return {
restrict: "A",
transclude: true,
scope: {
name: "@name",
client: "=client"
}
};
});
关于javascript - 使用指令创建隔离范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168000/