【问题标题】:Local image path in AngularJS/JavasScriptAngularJS/Javascript 中的本地图像路径
【发布时间】:2016-07-11 01:49:38
【问题描述】:

我想根据事件创建背景图像更改(特别是选择选项更改),但我无法在本地环境中获取图像路径。

我的图片路径在目录: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>

【问题讨论】:

标签: javascript css angularjs filepath


【解决方案1】:

为背景创建不同的类。 在 element 上使用 ng-class 根据 select 选项触发样式更改

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>

【讨论】:

  • 尝试使用此方法,但无法访问选择选项。我在我的原始问题中输入了我的 HTML 供我选择。会是 {'yellow': options.yellow...{'yellow': subject.yellow... 之类的吗?
  • 我做得更简单,在 plunker 上查看:plnkr.co/edit/MWgT4N8v2GscL3XmIcb9?p=preview
  • 呃,由于某种原因,它没有读取我的 CSS 中的类。 .yellow { background: .... 没有出现在元素检查中
  • 当我使用 class 而不是 ng-class 时它正在工作,奇怪
  • 尝试在 plunker 中重现您的案例并提供指向它的链接,以便我们查看所有相关代码
【解决方案2】:

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

【讨论】:

  • 这也可以,我只是担心在本地或现场使用时会出现不同的结果。
猜你喜欢
  • 2022-07-22
  • 1970-01-01
  • 2013-02-23
  • 2023-03-04
  • 2015-03-11
  • 2013-04-03
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
相关资源
最近更新 更多