我可以使用$ scope变量作为div background-image

时间:2014-08-14 17:11:49

标签: javascript jquery html css angularjs

我试图通过AngularJS $范围变量设置div background-image。 这就是我所拥有的:

$scope.destination1 = 'web/images/' + obj.FirstPerson + '.png';

然后在标记中,我有这个:

<div style="background-image:url(destination1)"  class="destination"></div>

我此时正在学习AngularJS,所以请原谅那些熟悉AngularJS如何工作的人。我们可以这样做吗?

更新: 在第一次回复之后,我做了更改,现在div看起来像这样:

<div id="destination" ng-style="{'background-image':'url({{destination1}})'}"  class="destination"></div>

在浏览器中将其翻译为: http://i.gyazo.com/e9e08f738d8ea52ed1ca5e0338692f65.png

正如您所看到的,虽然正确填充了ng-class属性,但background-image属性来自无处,没有赋值。 知道发生了什么吗? 再次感谢

1 个答案:

答案 0 :(得分:1)

ng-style的正确语法是:

 <div ng-style="{'background-image':'url({{re.url}})'}" ></div>

JSFiddle:http://jsfiddle.net/U3pVM/7194/

您也可以使用自定义指令:

app.directive('backgroundImageDirective', function () {
    return function (scope, element, attrs) {
        element.css({
            'background-image': 'url(' + attrs.backgroundImageDirective + ')',
            'background-repeat': 'no-repeat',
        });
    };
});

例如:

<div ng-repeat="re in recipes">
<div background-image-directive="{{re.url}}" style="height: 100px"></div>
</div>

JSFiddle:http://jsfiddle.net/U3pVM/7193/

不要忘记:

<div ng-style="'{{re.url}}' != '' && {'background-image':'url({{re.url}})'}" style="height: 100px"></div>

更新:

<div ng-controller="UserController" ng-app="myApp">
           <div ng-style="{'background-image':'url({{destination1}})'}" style="height: 100px"></div>
</div>

var app = angular.module('myApp', []);
app.controller("UserController", function ($scope) {

    $scope.destination1="http://scalabilitysolved.com/content/images/2014/May/stackoverflow.png";
});

JSFiddle:http://jsfiddle.net/U3pVM/7927/