I had the intention to use one template across several views having different controllers.
But now I realize that I cannot just write universal binding in templates because values will be put inside $scope.concreteControllerName
.
Angular docs for ngInclude say that
This directive creates new scope.
I could use ng-init
directive and pass controller instance to template's scope:
<ng-include src="..." ng-init="controller=concreteControllerName"/>
or even better
<ng-include src="..." ng-init="model=getModelForTemplate()"/>
and then write {{controller.boundvalue}}
in template.
That is a working solution, I guess.
And here I'd like to know whether other better approaches exist and if not, should templates always be used with some notion of passed model to abstract away from parent scope?
Use John Papa's controllerAs View Syntax and controllerAs with vm. You specify different controllers in the ng-include
directives but use the same src html template. The common vm
variable name is used in the template.
index.html
<div ng-include ng-controller="controllerOne as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerTwo as vm" src="'same.html'"></div>
<div ng-include ng-controller="controllerThree as vm" src="'same.html'"></div>
controllerOne.js
function controllerOne() {
var vm = this;
vm.name = 'Controller One!';
sharedTemplate.html
<div>{{vm.name}}</div>
Here is a full working version: Full Working Code in Plunker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With