具有插值表达式的Angularjs ng-style

时间:2017-09-23 05:46:21

标签: javascript html css angularjs

Angularjs v1.5.9:ng-style(ngStyle)

我的指令模板中有一个简单的 div ng-style 命令,我使用插值表达式在运行时获得不同的样式:

<div class="large-1 tile tile-plain"
      ng-style="{'background-image': 'url(assets/images/km-types/ico-{{iconMap[item.doctype]}}.png)'}">
</div>

指令如下:

 .directive('knowledgeItemIcon', function () {
      return {
          restrict: 'E',
          templateUrl: 'templates/item-icon.html',
          scope: {
            item: '='
          },
          link: function (scope,element,attrs) {
            scope.iconMap = {
              'howto': 'pen',
              'reference': 'settings',
              //...
            };
          }
        };
      });

iconMap 是指令链接函数中定义的静态数组。 docktype 是范围内商品的属性。

但是当模板呈现给浏览器时,我得到了:

<knowledge-item-icon item="vm.item" class="ng-isolate-scope">
    <div class="large-1 tile tile-plain" ng-style="{'background-image': 'url(assets/images/km-types/ico-phone.png)'} style="background-image: url("assets/images/km-types/ico-.png");">
    </div>
</knowledge-item-icon>

ng-style 中,似乎有正确的字符串,其中ico-phone.png,但在样式属性中为null。 我检查了item和iconMap对象都没有未定义,但为什么我在Web应用程序中有这个差异?

目前,我在div元素中添加 img 节点和 ng-src 命令,如:

<img ng-src="assets/images/km-types/ico-{{iconMap[item.doctype] || default}}.png" alt="">

它可以转换为正确的字符串:

<img ng-src="assets/images/km-types/ico-phone.png" alt="" src="assets/images/km-types/ico-phone.png">

2 个答案:

答案 0 :(得分:0)

您的ng-style代码中有拼写错误。

更改

<div ng-style="{'background-image': 'url(assets/images/km-types/ico-{{iconMap[item.doctype]}}.png)''}">

<div ng-style="{'background-image': 'url(assets/images/km-types/ico-{{iconMap[item.doctype]}}.png)'}">

请参阅下面的示例。

var app = angular.module("app", []);

app.controller("MainController", function($scope) {

  $scope.item = {
    "doctype": "test"
  }

  $scope.iconMap = {
    "test": "test-image"
  }

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>


<div ng-app="app" ng-controller="MainController">

  <div ng-style="{'background-image': 'url(assets/images/km-types/ico-{{iconMap[item.doctype]}}.png)'}">

  </div>

</div>

答案 1 :(得分:0)

相反,为了编写复杂的HTML,我建议您使用样式方法或值

<div class="large-1 tile tile-plain"
      ng-style="{'background-image': 'url(assets/images/km-types/ico-{{iconMap[item.doctype]}}.png)'}">
</div>

成为:

<div class="large-1 tile tile-plain"
     ng-style="getStyle(item.doctype)">
{{candidate.name}}
</div>

其中getStyle是:

$scope.getStyle = function(type){
  return {
    'background-image': "url(assets/images/km-types/ico-" + iconMap[type] + ".png)"    
  }      
}

更明确的方式

some Demo in Fiddle