Manipulating inline style with angular does not work in IE

后端 未结 3 1485
傲寒
傲寒 2020-12-06 04:05

I wanted to set the position of a div based on the return value of a function in an angular controller

The following works fine in FireFox and in chrome but in Inter

相关标签:
3条回答
  • 2020-12-06 04:42

    If you want to use angular binding expression {{}} just like normal style attribute like style="width:{{someScopeVar}}", use ng-attr-style and it will work perfectly IE (and obviously other smarter ones) :)

    check my jsFiddle ... Checked with Angular JS 1.4.8

    here I have shown the usage of style, ng-style and ng-attr-style

    THE 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>
    

    THE JS

    var app = angular.module('app', []);
    
    app.controller('controller', function($scope) {
    
        $scope.bgColor = "yellow";        
        $scope.styleObject = {"background": "yellow"};
    });
    
    0 讨论(0)
  • 2020-12-06 04:50

    You must use ng-style instead of style, otherwise some browsers like IE will remove invalid style attribute values (presence of {{}} etc makes it invalid) before even angular has a chance to render it. When you use ng-style angular will calculate the expression and add the inline style attributes to it.

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

    Since you are anyways calculating the position you could as well add % from the position and send it. Also remember that calling a function in ng-repeat will invoke the function every digest cycle, so you may want to be careful not to do too much intensive operations inside the method.

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

    and return

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

    Demo

    0 讨论(0)
  • 2020-12-06 05:06

    Yes, ng-style will work to resolve this problem. You can use conditionally style using ternary operator.

    HTML:

    <div ng-style="{'display':showInfo?'block':'none'}">
    </div>
    
    0 讨论(0)
提交回复
热议问题