【发布时间】:2017-02-07 13:18:41
【问题描述】:
我有一个带有模板的contactForm 指令,该指令放置在多个位置。它看起来像这样:
.directive('contactForm', ['SecureCheckoutService', function(SecureCheckoutService) {
return {
templateUrl: 'template/contactForm.html',
replace: true,
restrict: 'E',
scope: {
'modelVar': '=',
},
require: '^form',
link: function (scope, element, attr, formCtrl) {
scope.form = formCtrl;
}
};
}])
指令模板如下所示:
<script type="text/ng-template" id="template/contactForm.html">
<div>
<div class="form-group"
ng-class="{ 'has-error' : form.fullname.$invalid && !form.fullname.$pristine}">
<label class="control-label">Name *</label>
<input class="textInput form-control" name="fullname" type="text"
ng-model="modelVar.fullname" ng-model-options="{ updateOn: 'blur'}" required ng-maxlength="500" update-model model="modelVar" update-data="updateData(data)" />
<span class="completed" ng-if="form.fullname.$valid"></span>
<span ng-show="form.fullname.$error.required && !form.fullname.$pristine"
style="text-align:right" class="help-block">Recipient name is required.</span>
<span ng-show="form.fullname.$error.maxlength"
style="text-align:right" class="help-block">Maximum length is 500 characters.</span>
</div>
</div>
</script>
在那个指令模板中我有另一个自定义指令:
.directive('updateModel', ['$compile', function ($compile) {
return {
restrict: 'A',
scope: {
'updateData': '&',
'model': '='
},
require: 'ngModel',
link: function link(scope, elem, attrs, modelCtrl) {
scope.$watch(function () { return modelCtrl.$modelValue; }, function (newValue, oldValue) {
if (newValue != oldValue && modelCtrl.$valid){
scope.updateData({data: scope.model});
}
});
}
};
}])
联系表格指令是这样使用的:
<contact-form model-var="vm.model.billingInvoice" update-data="vm.updateInvoice(data)"></contact-form>
(在其他地方,我使用的是其他控制器功能和模型,而不是 vm.updateInvoice)
updateData 对象是控制器功能之一(值取决于联系表单的使用情况,因此我将其作为 update-data 参数放在指令范围内。 问题是我应该将该函数传播到 updateModel 指令并在模型更改时调用它。 如果我这样称呼它,则会执行适当的控制器功能,但数据未定义。 因此,我将 update-data 参数更改为:
update-data="vm.updateInvoice(vm.model.billingInvoice)" 并且成功了!直到我尝试在 ng-repeat 中添加联系表单指令,然后我再次未定义。 我想它与指令范围有关。
如果有任何帮助,我将不胜感激......
【问题讨论】:
-
我不会说这是重复的。如您所见,我在函数调用中使用命名参数。问题是控制器函数是从嵌套指令调用的。
标签: angularjs