AngularJS/JavasScript中的本地图像路径

Local image path in AngularJS/JavasScript

本文关键字:地图 图像 路径 JavasScript AngularJS      更新时间:2023-09-26

我想在事件发生时创建背景图像更改(特别是选择选项更改),但在本地环境中获取图像路径时遇到问题。

我的图像路径在目录中:http://localhost/webpage1/img/和图像yellow.jpg

我在我的应用程序(<div ng-controller="myCtrl" ng-style="style")中放入了一个ng-style指令,并将其与控制器绑定:

app.controller('myCtrl', function($scope) {
    $scope.options = [
        { type: 'yellow'},
        { type: 'green'}
    ];
    //default image
    $scope.subject = $scope.options[0].type;
    $scope.image = $scope.subject + ".jpg";
    $scope.style = {background: "url(" + $scope.image + ") no-repeat center center fixed"};
    ....
});

然而,我在检索图像的文件路径时遇到了麻烦。我不想列出整个文件路径,因为一旦我启用它,它就不一样了,所以像$scope.filepath = 'localhost/webpage1/img';这样的操作看起来非常混乱和丑陋。

编辑:我的选择选项

<select ng-model="subject" name="subject" class="subject" >
    <option ng-repeat="type in options">{{ type.type }}</option>
</select>

为背景创建不同的类。在元素上使用ng类来触发基于选择选项的样式更改

var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
  $scope.options = [
        { type: 'yellow'},
        { type: 'green'}
    ];
});
/* Put your css in here */
.foo {
  width: 100px;
  height: 100px;
  background-repeat: no-repeat;
  background-position: center;
}
.yellow {
  background-image: url(http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg);
}
.green {
  background-image: url(http://im.rediff.com/news/2015/dec/24tpoty20.jpg);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app">
<div ng-controller="MainCtrl">
  <select ng-model="subject" name="subject" class="subject" >
    <option ng-repeat="type in options">{{ type.type }}</option>
  </select>
  <div class="foo" ng-class="subject"></div>
</div>
</body>

要解决您的具体问题:有多种方法可以做到这一点,但您可以注入$location并为图像构建url。