【问题标题】:Can I use a $scope variable as a div background-image我可以使用 $scope 变量作为 div 背景图像吗
【发布时间】:2014-10-08 10:34:42
【问题描述】:

我正在尝试通过 AngularJS $scope 变量设置一个 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 属性来自任何地方,没有分配任何值。 知道发生了什么吗?

【问题讨论】:

  • 你用的是哪个版本?

标签: javascript jquery html css angularjs


【解决方案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/

【讨论】:

  • 您好,谢谢。我可以使用我的 $scope.destination1 变量而不是 re.url 吗?
  • 你使用 {{destination1}}
  • @user3763877 请检查我在初始内容中所做的更新问题,谢谢
猜你喜欢
  • 2021-11-21
  • 2011-11-11
  • 1970-01-01
  • 2013-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
相关资源
最近更新 更多