如何避免在HTML中使用ng repeat对url名称进行硬编码

How to avoid hard-coding url names in HTML with ng-repeat

本文关键字:url 编码 repeat HTML 何避免 ng      更新时间:2023-09-26

在解释这个问题之前,我想先介绍一下我的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。