Inherit an external controller scope from ng-include without a service?

In AngularJS, is it possible to inherit the scope of the parent controller from the enabled partial instead of passing data through the injected service?

Example:

Let's say the ParentCtrl scope looks like this: { testData: 'testing stuff' }

 <div ng-controller="ParentCtrl"> Here we're defined: {{testData}} <div ng-include="'partial.html'"></div> </div> 

And inside partial.html :

 <em>Inherited: {{testData}}</em> 

Thus, a partial element does not even need its own controller. If this is not possible, and you can only transfer injected data between controllers through the service, why did Angular do this?

+8
javascript angularjs angularjs-scope
source share
2 answers

Yes, actually, how it works by default. ng-include always creates a new scope and

A "massive region" (prototype) inherits properties from its parent sphere.

See area documents.

Here is an example of a plunker.

Edit: Also, I just noticed a syntax problem in the original question. The template must be surrounded by single quotes. Change <div ng-include="partial.html"></div> to <div ng-include="'partial.html'"></div>

+5
source share

Playing with the Plunkr example in the ngInclude documentation , I can access the scope of the parent controller from partial. For example, change the contents of template1.html to:

 Content of template1.html {{ template }} 

A new scope is created in ngInclude documents, which means you will need to follow the best angular practice of “having a point in your scope” (accessing objects in the scope instead of primitive values) to avoid problems with broken links. You can check this question for more information.

0
source share

All Articles