我有他们的背景图片范围,但我无法弄清楚如何让他们改变。我尝试了几种变体,但都没有通过。这是代码:
<div ng-controller="mainController" class="main">
<div ng-repeat="land in lands" class="col-md-9" ng-style="{ 'background-image': 'url({{ land.cover }})'}">
<p>{{ land.name }}</p>
</div>
</div>
使用Javascript:
app.controller('mainController', ['$scope', function($scope) {
$scope.lands = [
{
cover: 'img/norway.jpg',
cover1: 'img/norway1.jpg',
name: 'Norway'
},
{
cover: 'img/sweden.jpg',
cover1: 'img/sweden1.jpg',
name: 'Sweden'
},
{
cover: 'img/denmark.jpg',
name: 'Danmark'
},
{
cover: 'img/iceland.jpg',
name: 'Iceland',
},
{
cover: 'img/finland.jpg',
name: 'Finland'
},
{
cover: 'img/estonia.jpg',
name: 'Estonia'
}
];
}]);
答案 0 :(得分:4)
您不能在表达式上下文中使用插值标记。应该是:
<div ng-controller="mainController" class="main">
<div ng-repeat="land in lands" class="col-md-9"
ng-init="coverImage = land.cover"
ng-mouseover="coverImage = land.cover"
ng-mouseout="coverImage = land.cover1"
ng-style="{ 'background-image': 'url(' + coverImage + ')' }">
<p>{{ land.name }}</p>
</div>
</div>
答案 1 :(得分:2)
由于您正在尝试响应DOM,因此执行此操作的角度方式是创建指令。
工作代码可用here。解决方案的摘要是:
您的DOM将更改为:
<div ng-controller="MainController as ctrl">
<div ng-repeat="land in ctrl.lands" hover-bg-change default-bg="land.cover" hover-bg="land.cover1" class='tile'>
<p>{{ land.name }}</p>
</div>
</div>
该指令将如下所示:
app.directive('hoverBgChange', ['$parse', function ($parse)
{
return {
restrict: 'A',
link: function (scope, $el, attrs)
{
var defaultBg = $parse(attrs.defaultBg)(scope);
var hoverBg = $parse(attrs.hoverBg)(scope);
$el.css('background-image', 'url('+defaultBg+')');
$el.on('mouseover', function ()
{
$el.css('background-image', 'url('+hoverBg+')');
})
.on('mouseout', function ()
{
$el.css('background-image', 'url('+defaultBg+')');
});
}
}
}])
答案 2 :(得分:0)
你无法一次性使用它。 我的解决方案是 将css定义为
a = a - b
标记
.hover-out{
background-image: url('img/norway.jpg');
}
.hover-in{
background-image: url('img/norway1.jpg');
}