我想使用$ document从输入字段中获取服务器值。
var base_url = $document[0].getElementById('BaseUrl').value;
基本网址用于抓取模板。
var base_url = $document[0].getElementById('BaseUrl').value;
$routeProvider.when('/alert', {
controller: function () { },
templateUrl: base_url + '/partials/instances.html'
});
由于$ document会抛出一个未知的错误,我猜它在配置中不可用?有没有办法找出可用的和不可用的?我也可以使用$ http从服务器获取数据,但这也不可用。
答案 0 :(得分:16)
AngularJS模块分两个阶段进行自举:
Configuration phase
只有提供者和常量可用。Run phase
其中服务基于已注册的提供程序进行实例化。在这个阶段,常量仍然可用,但不是提供者。AngularJS documentation(部分:“模块加载和依赖性”)提供了对此的见解:
模块是配置和运行块的集合 在引导过程中应用于应用程序。在其中 最简单的形式模块由两种块的集合组成:
配置块 - 在提供商注册期间执行 和配置阶段。只能注入提供者和常量 到配置块。这是为了防止意外实例化 在完全配置之前的服务。
运行块 - 获取 在创建注射器后执行并用于启动注射器 应用。只有实例和常量才能注入运行 块。这是为了防止进一步的系统配置 申请运行时间。
鉴于上述情况,您只能注入常量和提供者(在API文档中标有Provider
后缀)。这可能会回答您的问题,但无法解决您的模板加载问题......
我想知道你是否不能简单地在HTML中使用基本标签,然后只使用相对路径(到基础)而不指定绝对路径?就像(如果基础配置正确):
$routeProvider.when('/alert', {
controller: function () { },
templateUrl: 'partials/instances.html'
});
答案 1 :(得分:16)
虽然这个问题已得到普遍回答,但这里针对问题中使用的具体示例进行了一些补充:
如何使用角度常量来定义部分的baseUrl(或定义表示服务器值并使其可用于配置的其他常量):
// file: app.js
'use strict';
/* App Module */
angular.module( 'myApp', [] )
// define the templateBaseUrl
.constant( 'templateBaseUrl', 'themes/angular/partials/' );
// use it in configuration
.config(['$routeProvider','templateBaseUrl', function($routeProvider,templateBaseUrl) {
$routeProvider
.when( '/posts', {
templateUrl : templateBaseUrl + 'post-list.html',
controller : PostListCtrl
})
.when( '/posts/:postId-:slug', {
templateUrl : templateBaseUrl + 'post-view.html',
controller : PostViewCtrl
})
.when( '/about', {
templateUrl : templateBaseUrl + 'about.html',
controller : AboutPageCtrl
})
.when( '/contact', {
templateUrl : templateBaseUrl + 'contact.html',
controller : ContactPageCtrl
})
.otherwise({
redirectTo: '/posts'
})
;
}]);
在我看来,这有几个好处:
通常,我不会将此解决方案与上面的硬编码值一起使用。这只是一个以最简单的方式展示要做什么的例子。为了能够在您的服务器上复制您的应用程序,请在索引文件中定义app.js之外的值,并生成必要的服务器端:
// file: index.php
<?php
// only depends on your project layout
$angularPartialsBaseUrl = 'themes/angular/partials/';
// this will change when you move the app around on the server
$themeBaseUrl = $_SERVER['REQUEST_URI'] . 'themes/angular';
?><!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Yii Blog Demo</title>
<script>
var myNS = myNS || {};
myNS.appConfig = myNS.appConfig || {};
myNS.appConfig.templateBaseUrl = '<?php echo $angularPartialsBaseUrl; ?>';
</script>
<script src="<?php echo $themeBaseUrl; ?>/js/vendor/angular/angular.js"></script>
<script src="<?php echo $themeBaseUrl; ?>/js/app.js"></script>
</head>
[...]
在app.js中:
// file: app.js
'use strict';
/* App Module */
angular.module( 'myApp', [] )
// define the templateBaseUrl using external appConfig
.constant( 'templateBaseUrl', myNS.appConfig.templateBaseUrl );