如果我将 ui-view 嵌套在 transclude=true 的指令内,则 View 内容不会加载。无需干预指令即可正常工作。
因此页面包含:
<body>
<div ng-controller="MainController">
<div ui-view="sampleView"></div>
</div>
</body>
出现sampleView内容。
但是如果我放
<body>
<div ng-controller="MainController">
<div sample-directive>
<div ui-view="sampleView"></div>
</div>
</div>
</body>
然后 View 内容不会出现。
我创建了一个简单的 html 页面来演示该问题,请参见下文。
据我所知,Angular 编译过程确实正确地调用了 Angular-UI 中 ui-view 指令中的 updateView,并且确实构建了 View 内容并将其插入到 Sample-directive 节点下的 dom 中,但是这似乎不是实际可见的样本指令节点,而是它的克隆。我猜这与编译顺序有关,因此我需要在指令中做一些巧妙的事情,但我在 Angular api 帮助中找不到涵盖这一点的任何内容。
我尝试添加一个后链接函数并从那里调用 $transclude,但这没有什么区别。
任何人都可以建议我需要在指令中添加什么,这样才能起作用。 谢谢
更新 进一步调查的新信息: 看来原因是这样的(目前还不是解决方案,但我可以明白为什么会发生)。 在 Angular 的函数 applyDirectivesToNode(Angular.js 第 5919 行)中,如果指令指定 transclude=true,则将克隆原始指令节点以制作模板节点。即模板不是 dom 中可见的原始节点。现在,当调用 angular-ui-router.js 第 2204 行中 ui-view 的编译函数时,它会获取 ui-view 节点的父节点的副本,并将其存储在parentEl中。但是,这就是问题发生的地方 - 这个父节点是 ui-view 节点的 dom 中的父节点。它肯定不是链接后实际上最终出现在 dom 中的父级实例。稍后,当 ui-view 更新初始路由更改时,它会构建 View 内容并将其插入到 ParentEl 下(angular-ui-router.js 第 2273 行),但正如我们之前所见,链接后这并不在可见 dom 中。它是源 html 节点,而不是通过编译和链接嵌套 ui-view 的指令创建的克隆。
我认为这可能是 ui-view 中的一个错误。
可能有一种方法可以向指令添加解决方法,以获取链接后 View 实例并将其放入指令中。如果我弄清楚了,我会添加一个答案。
html 演示该问题如下:
<!DOCTYPE html>
<html lang="en" ng-app="viewInDirectiveApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>View inside a directive</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.js"></script>
<script src="modules/angular-ui-router.js"></script>
<script>
var viewInDirectiveApp = angular.module('viewInDirectiveApp', ['ui.router']);
viewInDirectiveApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('sampleState', {
url: '/sampleState',
views: {
sampleView: {
template: 'This is the view content',
controller: function ($scope) {
}
}
}
});
$urlRouterProvider.otherwise("/sampleState");
})
.controller('MainController', ['$scope',
function ($scope) {
}])
.directive('sampleDirective', function () {
return {
template: 'Start directive content <div ng-transclude></div> End directive content',
transclude: true
};
});
</script>
</head>
<body>
<div ng-controller="MainController">
Before sampleDirective
<div sample-directive>
Before sampleView
<div ui-view="sampleView"></div>
After sampleView
</div>
After sampleDirective
</div>
</body>
</html>
最佳答案
已确认 ui-router 0.2.8 中的错误:https://github.com/angular-ui/ui-router/issues/774
0.2.10 中已修复:https://github.com/angular-ui/ui-router/pull/858
关于javascript - 嵌套在指令中的 angular-ui View 不会加载 View 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21803661/