我想在事件(特别是选择选项更改)上创建背景图像更改,而我在本地环境中获取图像路径时遇到问题。
我的图片路径在目录中:http://localhost/webpage1/img/
,图片为yellow.jpg
我在我的应用程序(ng-style
)中添加了<div ng-controller="myCtrl" ng-style="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>
答案 0 :(得分:1)
为背景创建不同的类。 使用ng-class on元素根据选择选项
触发样式更改
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.options = [
{ type: 'yellow'},
{ type: 'green'}
];
});
&#13;
/* 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);
}
&#13;
<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>
&#13;
答案 1 :(得分:0)
解决您的具体问题: 有多种方法可以执行此操作,但您可以注入$location并为图像构建您的网址。