我有这条路线.
// 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 / one.html中使用ng-include包含partials / two.html时,它会正确显示它,但会创建一个不同的范围,因此我无法与之交互.
// 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>