Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

angularjs - How to include one partial into other without creating a new scope?

I've this routes.

// index.html
<div ng-controller="mainCtrl">
    <a href='#/one'>One</a>
    <a href='#/two'>Two</a>
</div>?????????
<div ng-view></div>

And this is how I'm loading the partials into my ng-view.

// app.js
?var App = angular.module('app', []);???????
App.config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/one', {template: 'partials/one.html', controller: App.oneCtrl});
    $routeProvider.when('/two', {template: 'partials/two.html', controller: App.twoCtrl});
  }]);

When I click the links, it shows me the appropriate markup inside the ng-view. But when I try to include partials/two.html inside partials/one.html using ng-include, it shows it properly but creates a different scope so I'm not able to interact with it.

// partials/two.html - markup
<div ng-controller="twoCtrl">I'm a heading of Two</div>

// partials/one.html - markup
<div ng-controller="oneCtrl">I'm a heading of One</div>
<div ng-include src="'partials/two.html'"></div>

? How do I resolve this problem? Or Is there any other way to achieve the same result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can write your own include directive that does not create a new scope. For example:

MyDirectives.directive('staticInclude', function($http, $templateCache, $compile) {
    return function(scope, element, attrs) {
        var templatePath = attrs.staticInclude;
        $http.get(templatePath, { cache: $templateCache }).success(function(response) {
            var contents = element.html(response).contents();
            $compile(contents)(scope);
        });
    };
});

You can use this like:

<div static-include="my/file.html"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...