如何避免在HTML中使用ng repeat对url名称进行硬编码
How to avoid hard-coding url names in HTML with ng-repeat
在解释这个问题之前,我想先介绍一下我的HTML代码
<div ng-repeat="item in employeeNames">
<span>
<img data-ng-src="http://192.128.1.125/uploads/images/{{item.photoName}}">
</span>
{{item.name}}
</div>
其中CCD_ 1包含具有CCD_ 2和CCD_。
$sope.employeeNames=
[{
name:Rob,
photoName:rer343983j38u38r8u3
},
{
name:Alice,
photoName:dfgrt564yt546y565556r4t
},
]
我如何避免在html中对url http://192.128.1.125/uploads/images/
进行硬编码,因为每次url更改时我都需要更改?
创建一个为urls
服务的简单服务,因此,如果您需要更改url,您只需要更改此服务。
例如:
var app = angular.module('app', []);
app.factory('URLs', function() {
var domain = 'http://192.128.1.125/';
return {
uploadPath: {
url: domain+'uploads/images/'
},
appImagesPath: {
url: domain+'uploads/images/app/'
},
// for $httpa jax requests,
getUserDetails: {
url: domain+'user/details',
method: 'GET'
},
postLoginDetails: {
url: domain+'user/login',
method: 'POST'
}
}
});
在控制器中,
app.controller('testCtrl', ['$scope', '$http', 'URLs', function($scope, $http, URLs) {
$scope.uploadDir = URLs.uploadPath;
/*
*--------------------------------------------
* if you need to process `$http` ajax request.
*--------------------------------------------
*/
var httpConfig = {
method: URLs.getUserDetails.method,
url: URLs.getUserDetails.url,
data: {}
};
// OR
/*
* var httpConfig = URLs.getUserDetails;
*
* httpConfig['data'] = {pram1: 'data-value-1', param2: 'data-value-2'};
*/
$http(httpConfig).
.success(function(data, status, headers, config) {
}). error(function(data, status, headers, config) {
});
}]);
在HTML、中
<img data-ng-src="{{uploadDir+item.photoName}}">
您可以使用Angular的$location
服务,并通过使用给定的函数(如$location.host()
等)来构建链接。
我个人使用服务来提供的所有配置
angular.module('myApp').service('siteSettings', function(){
return {
host: 'http://localhost:5000',
userApi: '/users'
}
})
然后在任何地方,您都可以注入siteSettings
并像使用siteSettings.host
一样使用它
我的第一个想法是:相对简单的解决方案。为您的url进行配置。然后,您只需在控制器/链接中插入配置即可。这可以通过提供。。。https://docs.angularjs.org/api/auto/service/$provide
示例:
(function () {
angular.module("myApp", [])
.config(["$provide",
function ($provide) {
$provide.value("siteConfig", {
imgAssetServerUrl: "http://127.0.0.1/img"
});
}]);
})();
我的第二个想法是:使用相对url。
相关文章:
- 使用 POST 方法通过 ajax 发送的数据在发送到服务器之前是否必须进行 URL 编码
- PHP(PDO)url编码如何在javascript中解码?decodeURI?或解码URI组件
- 以 json 或 url 编码格式发送 js 模型
- 从函数调用控制器并向其传递 URL 编码参数
- PHP 通过 url 编码数据传递字符串
- 如何防止空格被 URL 编码为“javascript:”URL
- 将url编码的数据转换为JSON数组或js数组
- 从HTML5中URL编码的字符串中提取数据
- 我不知道如何写出URL编码的查询字符串
- xmlhttprequest中的url编码
- <输入类型='文件'>提供了URL编码的文件名,导致Android本机浏览器上的FileRea
- javascript中的Url编码
- Angular显示url编码错误,如何获得解码版本
- 最新的base64和url编码库
- 联系API时出现错误的URL编码
- 为什么对href属性使用url编码而不是html编码
- Ajax url编码问题
- Url编码的Javascript问题
- 我应该担心在form元素中使用GET不会;t自动对尖括号进行URL编码
- Node.js:由于URL编码的GET参数,导致外部资源的路径混乱