【发布时间】:2015-02-09 00:21:01
【问题描述】:
我想尽办法解决这个问题。假设我有这个自定义指令:
app.directive("selectInput",function($compile){
return {
restrict: "E",
templateUrl: 'js/angular-app/test.html',
scope: {
formName:'=',
inputName:"=",
nameInput: "@",
ngModel: "=",
},
transclude: true,
replace: true,
link: function(scope, element, attrs, ctrl) {
...
},
}});
这里是我的 templateurl test.html
<div
class="form-group"
ng-class="{'has-error has-feedback': formName.inputName.$invalid}">
<input type="text" name="{{nameInput}}" ng-model="ngModel"/></div>
还有电话
<form name="form" class="simple-form" novalidate>
<select-input
form-name="form"
input-name="fClase"
name-input="fClase"
ng-model="inputmodel">
</select-input></form>
问题出在 test.html 模板中,表达式 formName.inputName.$invalid 不起作用,我尝试 {{formName}}.{{inputName}}.$invalid 什么也没有,我还尝试更改 &, @ ... =? 的指令定义中的参数。
我无法合并这些表达式,感谢您的帮助。
更新,解决问题(感谢 Joe Enzminger):
最后我通过以下方式更改指令:
app.directive("selectInput",function($compile){
return {
restrict: "E",
templateUrl: 'js/angular-app/test.html',
scope: {
inputName: "@",
ngModel: "=",
},
require: ["^form"],
replace: true,
link: function(scope, element, attrs, ctrl) {
scope.form = ctrl[0];
...
},
}});
注意表单 attr 为 ctrl。
模板test.html
<div
class="form-group"
ng-class="{'has-error has-feedback': form[inputName].$invalid}">
<input type="text" name="{{nameInput}}" ng-model="ngModel"/></div>
在这里将formName.inputName.$invalid 更改为form[inputName].$invalid
最后是通话
<form name="form" class="simple-form" novalidate>
<select-input
input-name="fClase"
ng-model="inputmodel">
</select-input></form>
希望对你有用
【问题讨论】:
-
使用 ng-model 以外的名称作为模型的名称(ng-model 会与 angular ng-model 指令混淆(请改用“model-name”之类的名称。您可以然后在您的 ng-class 表达式中使用 formName[modelName].$invalid。但是,请查看下面我的答案,以获得更简洁的替代实现。
标签: angularjs angularjs-scope angular-directive angularjs-templates