新しいスコープを作成せずに、ある部分を他の部分に組み込むにはどうすればよいでしょうか? 質問する

新しいスコープを作成せずに、ある部分を他の部分に組み込むにはどうすればよいでしょうか? 質問する

私はこのルートを持っています。

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

そして、これが私が部分を にロードする方法です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});
  }]);

リンクをクリックすると、ng-view 内に適切なマークアップが表示されます。しかし、を使用してpartials/two.html内部に含めようとすると、適切に表示されますが、別のスコープが作成されるため、操作できません。partials/one.htmlng-include

// 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>

この問題を解決するにはどうすればよいですか? または、同じ結果を達成する他の方法はありますか?

ベストアンサー1

新しいスコープを作成しない独自の include ディレクティブを記述できます。例:

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);
        });
    };
});

次のように使用できます:

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

おすすめ記事