【问题标题】:Manipulating inline style with angular does not work in IE使用 Angular 操作内联样式在 IE 中不起作用
【发布时间】:2014-10-28 14:38:41
【问题描述】:

我想根据角度控制器中函数的返回值来设置 div 的位置

以下内容在 FireFox 和 chrome 中运行良好,但在 Internet Explorer 中 {{position($index)}}% 被解释为文字字符串值,因此无效

<div ng-repeat="item in items" style="left:{{position($index)}}%"></div>

这是一个问题的例子:

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

app.controller('controller', function($scope) {

    $scope.items=[1,2,3,4,5,6,7,8,9,10];

    $scope.position=function(i){
        var percent =[5,10,15,20,25,30,35,40,45,50,55,60,65,70];
        return percent[i+1];
    }
});

这里有一个Fiddle来演示

有人对如何纠正有建议吗?

【问题讨论】:

    标签: html angularjs internet-explorer angularjs-ng-repeat inline-styles


    【解决方案1】:

    您必须使用ng-style 代替样式,否则某些浏览器(例如IE)会在Angular 有机会渲染它之前删除无效的样式属性值({{}} 等的存在使其无效)。当您使用ng-style 时,angular 会计算表达式并为其添加内联样式属性。

    <div ng-repeat="item in items" ng-style="{left: position($index) + '%'}"></div>
    

    既然您无论如何都在计算位置,您也可以从position 中添加% 并发送它。还要记住,在 ng-repeat 中调用函数会在每个摘要循环中调用该函数,因此您可能需要注意不要在方法内执行太多密集操作。

     <div ng-repeat="item in items" ng-style="{left: position($index)}">{{item}}</div>
    

    然后返回

      return percent[i+1] + "%";
    

    Demo

    【讨论】:

      【解决方案2】:

      如果你想像style="width:{{someScopeVar}}"这样的普通样式属性一样使用角度绑定表达式{{}}, 使用 ng-attr-style 它将完美运行 IE(当然还有其他更智能的):)

      检查我的jsFiddle ... 使用 Angular JS 1.4.8 检查

      这里我展示了styleng-styleng-attr-style的用法

      HTML

      <div ng-app="app">
          <div ng-controller="controller">
      
              <div style="background:{{bgColor}}">
                  This will NOT get colored in IE
              </div>
      
              <div ng-attr-style="background:{{bgColor}}">
                  But this WILL get colored in IE
              </div>
      
              <div ng-style="styleObject">
                  And so is this... as this uses a json object and gives that to ng-style
              </div>
      
          </div>
      </div>
      

      JS

      var app = angular.module('app', []);
      
      app.controller('controller', function($scope) {
      
          $scope.bgColor = "yellow";        
          $scope.styleObject = {"background": "yellow"};
      });
      

      【讨论】:

        【解决方案3】:

        是的,ng-style 可以解决这个问题。您可以使用ternary operator 有条件地使用样式。

        HTML:

        <div ng-style="{'display':showInfo?'block':'none'}">
        </div>
        

        【讨论】:

          猜你喜欢
          • 2018-09-26
          • 2014-10-14
          • 1970-01-01
          • 1970-01-01
          • 2017-12-19
          • 2017-10-21
          • 1970-01-01
          • 2011-03-15
          • 1970-01-01
          相关资源
          最近更新 更多