我正在实现一个自定义输入小部件。真正的代码比较复杂,但一般是这样的:
app.directive('inputWidget', function () {
return {
replace:true,
restrict: 'E',
templateUrl:"inputWidget.html",
compile: function (tElement, tAttributes){
//flow the bindings from the parent.
//I can do it dynamically, this is just a demo for the idea
tElement.find("input").attr("placeholder", tAttributes.placeholder);
tElement.find("input").attr("ng-model", tElement.attr("ng-model"));
}
};
});
inputWidget.html:
<div>
<input />
<span>
</span>
</div>
使用它:
<input-widget placeholder="{{name}}" ng-model="someProperty"></input-widget>
上面的代码可以正确显示占位符,因为它使用与父级相同的范围:http://plnkr.co/edit/uhUEGBUCB8BcwxqvKRI9?p=preview
我想知道是否应该使用隔离范围,如下所示:
app.directive('inputWidget', function () {
return {
replace:true,
restrict: 'E',
templateUrl:"inputWidget.html",
scope : {
placeholder: "@"
//more properties for ng-model,...
}
};
});
这样,该指令就不会与父指令共享相同的范围,这可能是一个很好的设计。但问题是,当我们在其上放置与 DOM 相关的属性(占位符、类型、必需的...)时,这个隔离范围定义很快就会变得困惑,并且每次我们需要应用新的指令(输入小部件上的自定义验证),我们需要在隔离范围上定义一个属性来充当中间人。
我想知道始终在指令组件上定义隔离范围是否是一个好主意。
在这种情况下,我有 3 个选择:
- 使用与父级相同的范围。
- 按照我上面所说的使用隔离范围。
- 使用隔离范围,但不将 DOM 相关属性绑定(bind)到它,以某种方式直接从父级传递 DOM 相关属性。我不确定这是否是个好主意,也不知道该怎么做。
请多多指教,谢谢。
最佳答案
如果输入小部件配置很复杂,我将使用选项属性以及隔离范围来使属性显式且强制:
<input-widget options="{ placeholder: name, max-length: 5, etc }"
ng-model="name"></input-widget>
如果您有选项模型和 ngModel,则无需流动任何 DOM 属性:
app.directive('inputWidget', function () {
return {
replace:true,
restrict: 'E',
templateUrl:"inputWidget.html",
scope: { options:'=', ngModel: '='}
};
});
在模板中,您可以将属性绑定(bind)到 $scope View 模型,就像平常一样:
<div>
<input placeholder="{{options.placeholder}}" ng-model="ngModel"/>
<span>
{{options}}
</span>
</div>
就我个人而言,在进行重用开发时,我更喜欢使用属性作为配置指令和隔离范围的手段,以使其更加模块化和可读。它的行为更像一个组件,通常不需要任何外部上下文。
但是,有时我发现具有子/继承作用域的指令很有用。在这些情况下,我通常“要求”父指令来提供上下文。这对指令一起工作,以便更少的属性必须流向子指令。
关于angularjs - 在这种情况下我应该使用隔离范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425512/