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

My intention was to use one template for multiple views with different controllers.

But now I understand that I can’t just write a universal binding in templates, because the values ​​will fit inside $scope.concreteControllerName .

Angular docs for ngInclude say that

This directive creates a new scope.

I could use the ng-init directive and pass the controller instance to the template area:

 <ng-include src="..." ng-init="controller=concreteControllerName"/> 

or even better

 <ng-include src="..." ng-init="model=getModelForTemplate()"/> 

and then write {{controller.boundvalue}} in the template.

This is a working solution, I think.

And here I would like to know if there are other more effective approaches, and if not, should templates always be used with some concept of the past model to abstract from the parent area?

+5
source share
1 answer

Using Papa the John controllerAs View Syntax and controllerAs with uta>. You specify different controllers in ng-include directives, but you use the same src html template. The template uses the generic variable name vm .

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 the full working version: Full working code in Plunker

+3
source

Source: https://habr.com/ru/post/1204929/


All Articles