问题
I'd like to reuse an express included template multiple times and selectively bind it to different properties of the scope as follows:
<div ng-show="isCoApplicant" bind-to="applicant in data.coApplicant">
<% include ../row-templates/applicant-row %>
</div>
Similar to the behavior of ng-repeat which creates a child scope for the row and sets a property on it according to the expression 'applicant in data.coApplicant', and the row inputs can be bound to 'applicant' via ng-model.
I've spent some time researching various angular directives including ng-controller, ng-include, ng-model, etc. and I can't seem to put it together.
Appreciate any help on figuring this binding out.
回答1:
Use a directive. In your HTML you can invoke the directive with <my-applicant>
, you can use it multiple times, and the data like data.coApplicant
can be binded to each directives isolate scope via applicantData
attribute.
HTML
<my-applicant applicantData='data.coApplicant'></my-applicant>
Directive JS
.directive('myApplicant', function() {
return {
restrict: 'E',
scope: {
applicantData: '='
},
template: '<div ng-show="isCoApplicant"' +
'bind-to="applicant in data.coApplicant">' +
'<% include ../row-templates/applicant-row %></div>'
};
});
For further info on directives read the Docs developers guide https://docs.angularjs.org/guide/directive
回答2:
@cheekybastard put me on the right track with the directive scope and template properties. In the end I wanted a reusable directive for dynamically including a template and binding a specific property from the parent scope into the template's scope. I was surprised angular didn't already have something like this, I guess my use case is not too common.
This is what I ended up with:
HTML
<div bind-template-to="data.coApplicant" template-url="/row-templates/applicant-row.ejs"></div>
Directive JS
.directive('bindTemplateTo', function() {
return {
restrict: 'A',
scope: {
data: '=bindTemplateTo'
},
templateUrl: function(element, attr) { return attr.templateUrl; }
};
});
Template
<input ng-model="data.first" ...>
It seems you need to use a template via template or templateUrl property in the directive in order for the isolate scope to be available to your elements. I.e. if you simply use a directive to create the isolate scope for the div and hope that elements within the div will bind to the new isolate scope you will be disappointed.
Thanks for your help.
来源:https://stackoverflow.com/questions/29836253/angularjs-reuse-template-and-bind-to-different-properties-within-the-same-scope