admin管理员组

文章数量:1431691

I have been trying to use ng-style all morning however it is not working as expected. In my directive I did something similar to this:

this.width = this.width+'px';
scope.myStyle = {width: this.width};

and in my html I have:

<div ng-style="myStyle" class="no-margin"
style="position:absolute;">

I have been trying to use ng-style all morning however it is not working as expected. In my directive I did something similar to this:

this.width = this.width+'px';
scope.myStyle = {width: this.width};

and in my html I have:

<div ng-style="myStyle" class="no-margin"
style="position:absolute;">
Share Improve this question edited Jan 31, 2017 at 10:36 Devid Farinelli 7,5549 gold badges45 silver badges75 bronze badges asked Apr 14, 2015 at 15:16 BobDoleForPresidentBobDoleForPresident 5529 silver badges23 bronze badges 9
  • Does it get applied with wrong values? Not applied at all? Can you post the rest of the directive? – tymeJV Commented Apr 14, 2015 at 15:17
  • is your this doing the correct reference when assigning it to myStyle? – RobertoNovelo Commented Apr 14, 2015 at 15:18
  • The this is setting the right values. It seems to be the syntax. The strange thing is that this code works: <div ng-style="{{myStyle}}" class="no-margin" style="position:absolute;"> but I am unsure if I should use it because it shows an error in the HTML. That is pretty much the entirety of the code in that directive. There is also a watch function but is watching an unrelated variable. – BobDoleForPresident Commented Apr 14, 2015 at 15:22
  • I'm not sure an object is a correct usage for ng-style.. where have you seen this? – Omri Aharon Commented Apr 14, 2015 at 15:22
  • @OmriAharon here docs.angularjs/api/ng/directive/ngStyle – BobDoleForPresident Commented Apr 14, 2015 at 15:22
 |  Show 4 more ments

2 Answers 2

Reset to default 3

ng-style should contain an object, so change your code to this:

this.width = this.width+'px';
scope.myStyle = {width: this.width, position:'absolute'};

<div ng-style="myStyle" class="no-margin">

The way should be:

<div ng-style="{{ myStyle }}" class="no-margin">

Reason being that the {{ }} is how AngularJs determine which is a variable or hard text.

本文标签: javascriptNgstyle not workingStack Overflow