Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the best practices of using ngInclude with ControllerAs syntax?

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?

like image 898
Pavel Voronin Avatar asked Oct 21 '22 00:10

Pavel Voronin


1 Answers

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

like image 151
James Lawruk Avatar answered Oct 23 '22 19:10

James Lawruk