Skip to main content
 首页 » 编程设计

angularjs之如何在不创建新范围的情况下将一个部分包含到另一个中

2025年02月15日26www_RR

我有这条路线。

// 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.htmlpartials/one.html包含在 ng-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> 

我该如何解决这个问题?还是有其他方法可以达到相同的结果?

请您参考如下方法:

您可以编写自己的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>