虽然问题通常被回答,这里有一个小加成靶向在问题中使用的具体的例子:
如何使用的角度恒定定义你的泛音的的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'
})
;
}]);
在我看来,这有几个好处:
- 如果你移动你的意见,你只需要在一个单一的位置更新代码
- 如果你的谐音被深度嵌套项目布局中,“templateBaseUrl”不会造成尽可能大的噪音整个路径
- 你甚至可以在相对路径和绝对路径之间切换
- An answer to a similar question建议使用html的基本元素来删除对每个templateUrl预先添加baseUrl的需要。但是这也影响了网站上的所有其他资源。仅配置模板的基本url没有副作用
通常,我不使用此解决方案,并使用上面的硬编码值。这只是一个例子,以最简单的方式展示要做什么。为了能够复制左右你的应用服务器上,定义值app.js之外,在你的索引文件并生成必要的pathes服务器端:
// 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);
来源
2012-10-19 20:22:39
ben
看看这个答案︰http://stackoverflow.com/questions/17011616/using-a-relative-path-for-a-service-call-in-angularjs/17112017#17112017我认为这是一个更好的解决方案。 –