我正在学习 AngularJS,特别是学习指令。想要一个表单输入指令,我可以在我的所有表单上重复使用它来封装所有样板标记。尽管我无法在我的指令中使用两种方式进行绑定(bind)。它使用具有自己内部属性的隔离范围来存储输入字段的值。我已经在该内部属性上设置了一个 watch ,该属性正确地将隔离范围内的值推送到 Controller 范围内。我想弄清楚的是如何从 Controller 范围中获取初始值并将其设置为我的指令中的初始值。
Plunker 链接:http://embed.plnkr.co/TbVB0q9DHhBCVLQ4U64W/script.js
在第一个输入框中键入会更改 Controller 范围属性,但不会更改指令值。在第二个输入框中键入会更改指令和 Controller 属性。
我知道这可以使用属性来传递初始值。但是,我希望能够通过指令中的 ngModel 引用从 Controller 范围属性中提取值。
回答后编辑:
对于那些不确定为什么要完成学习指令的人。尤其是当 Angular 即使不使用指令也如此强大时。这是一个很好的理由。
在没有指令的情况下在我的表单上输入字段:
<div class="form-group">
<label for="firstName" class="col-sm-6 col-md-4 control-label">First Name</label>
<div class="col-sm-6 col-md-8" ng-class="{'has-error': userForm.firstName.$invalid}">
<input type="text" id="firstName" name="firstName" placeholder="First Name" ng-model="muState.currentUser.firstName" class="form-control" required
popover="Cannot be blank" popover-trigger="{{{true: 'mouseenter', false: 'never'}[userForm.firstName.$invalid]}}" />
</div>
</div>
使用我的指令后:
<ws-form-input input-name="firstName" input-label="First Name" input-placeholder="First Name"
ng-model="muState.currentUser.firstName"
required input-error="Cannot be blank"></ws-form-input>
通过努力。您将在学习的头痛与稍后的维护噩梦之间进行权衡。
最佳答案
我认为您可以通过使用隔离作用域的 '='
属性符号来完全简化您的指令。
像这样:
JavaScript
app.directive('inputDirective',function(){
return {
restrict: 'E',
replace: true,
scope: {ngModel: '='},
templateUrl: "directiveTemplate.html",
require: '^form',
link: function(scope, elem, attrs, ctrl){
scope.form = ctrl;
scope.required = false;
// If attribute required exists
if (attrs.required !== undefined) {
// ng-required takes a boolean which is read from this scope variable
scope.required = true;
}
}
};
});
HTML 指令
<div>
<input type="text" id="directiveInput"
ng-model="ngModel" class="form-control" ng-required="required"/>
<br/>
Isolated Scope value of the input box: {{ngModel}}
</div>
关于javascript - 表单输入指令与隔离范围的两种方式绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034397/