目标:创建一个隔离范围的指令,当应用于具有现有input
指令的ng-model
元素时,会任意约束模型的值,将更改反映回父作用域。使用“controller-as”命名完成所有这些操作。
例如,假设包含控制器为outerCtrl
,此模板表示可能使用上述指令:
<input ng-model="outerCtrl.value" my-directive>
以下代表myDirective
定义的一部分(缺少功能部分,表示为评论并且是实际问题):
angular.module('app').directive('myDirective', [function() {
return {
restrict: 'A',
scope: {},
require: 'ngModel',
controllerAs: 'myCtrl',
bindToController: true,
controller: controller: [function() {
var vm = this;
vm.magicValue = 'foo';
}],
// ----------
// Insert appropriate compile, link, etc. to ensure that if
// the user ever types the "magic value" in the input, then
// the parent model (outerCtrl.value) is set with the magic
// value; otherwise, the value set on the parent model should
// be "null" or "undefined." And, of course, if there is ever
// a programmatic setting of outerCtrl.value, that should be
// reflected down to the input while obeying the same rule -
// i.e., if some value other than the magic value is set, it
// should be ignored.
//
// Of critical importance: there may be other directives
// operating on the same ng-model within the isolate scope
// (or, rather, as child scopes of the isolate scope).
// These other directives should work in concert with
// myDirective. For example, one such directive might be a
// "typeahead" directive that manipulates the model based on
// selection from a dropdown list. This behavior can't be
// trampled by myDirective.
// ----------
};
}]);
使用隔离范围的主要动机是确保指令可重用。我没有使用包装器div
或其他元素在指令模板中包含input
的动机是为了更容易在任何现有的input
元素上使用该指令,从而也ng模型验证的优势可能已经在父范围内有效。
这可能吗?更重要的是,我是否应该尝试这样做,还是根据框架设计者的意图滥用ng-model / isolate范围/指令?